DEV Community

Shuichi
Shuichi

Posted on • Edited on

Python script to list unused IP addresses in AWS VPC Subnet

I wrote a Python script to list unused IP addresses (IPv4) in a subnet.

I have used Henry's post as a reference, thanks.

Mechanism

  1. Get the CIDR of specified subnet by DescribeSubnets
  2. Get the used private IP addresses in specified subnet by DescribeNetworkInterfaces = Used IP addresses
  3. Calculate the Unused IP addresses = "CIDR IP addresses" - "Used IP addresses" - "Reserved IP Addresses"

note

  • I used ipaddress module to calculate IP addresses within the CIDR.
  • I used "PrivateIpAddresses array" instead of "PrivateIpAddress" to extract both primary and secondary addresses from the NetworkInterface response.
  • Reserved IP addresses are described in official documentation

For example, if you create a VPC with CIDR block 10.0.0.0/24, it supports 256 IP addresses. You can break this CIDR block into two subnets, each supporting 128 IP addresses. One subnet uses CIDR block 10.0.0.0/25 (for addresses 10.0.0.0 - 10.0.0.127) and the other uses CIDR block 10.0.0.128/25 (for addresses 10.0.0.128 - 10.0.0.255).

Python script

https://github.com/shu85t/aws_describe_unused_ips

Requirements

  • >Python3.8
  • boto3
  • AWS Permissions
    • ec2:DescribeSubnets
    • ec2:DescribeNetworkInterfaces

Usage

export AWS_DEFAULT_REGION={region name}
export AWS_DEFAULT_PROFILE={aws profile name}
python describe_unused_ips.py {subnet-id}
Enter fullscreen mode Exit fullscreen mode
export AWS_DEFAULT_REGION=ap-northeast-1
export AWS_DEFAULT_PROFILE=my_aws_account
python describe_unused_ips.py subnet-000000000000
Enter fullscreen mode Exit fullscreen mode

output

subnet_id='subnet-000000000000' mode='normal'
cidr='10.1.0.0/24'
cidr_ips=['10.1.0.0', '10.1.0.1', '10.1.0.2', '10.1.0.3', '10.1.0.4', ...]
-----------
reserved_ips=['10.1.0.0', '10.1.0.1', '10.1.0.2', '10.1.0.3', '10.1.0.255']
-----------
used_ips=['10.1.0.39']
-----------
unused_ips=['10.1.0.4', '10.1.0.5', '10.1.0.6', ...]
-----------
cidr=10.1.0.0/24 cidr_ips=256 reserved=5 used=1 unused=250
Enter fullscreen mode Exit fullscreen mode

This post is an English rewrite of an post I wrote in Japanese.

Top comments (0)