All private IP addresses within a subnet on AWS
To get all the IP addresses in use within a subnet using Python on AWS, you can use the Boto3 library, which is the official AWS SDK for Python. This allows you to interact with AWS services like Amazon EC2, which provides information about your subnets.
import boto3
def get_used_ips(subnet_id):
ec2 = boto3.client('ec2')
used_ips = []
# Get all instances within the specified subnet
instances = ec2.describe_instances(Filters=[{'Name': 'subnet-id', 'Values': [subnet_id]}])
# Extract IP addresses from instances
for reservation in instances['Reservations']:
for instance in reservation['Instances']:
# Get the network interfaces attached to the instance
network_interfaces = instance['NetworkInterfaces']
for interface in network_interfaces:
# Extract primary and secondary private IP addresses
for private_ip in interface['PrivateIpAddresses']:
used_ips.append(private_ip['PrivateIpAddress'])
return used_ips
# Replace with your subnet ID
subnet_id = 'subnet-xxxxxxxxxxxxxxxxx'
used_ips = get_used_ips(subnet_id)
print(f"IP addresses in use within the subnet {subnet_id}:")
for ip in used_ips:
print(ip)