简体   繁体   中英

Python script to automate number of available ip addresses on my subnet

Can someone help me with creating a python script that will do these things. I am trying to learn how to automate things.

Run nmap quick scan and export to text file:

nmap -T4 -F 10.0.0.1/24 > nmap.txt

Cut text to list of IP's:

cat nmap.txt | grep "Nmap scan report" | awk '{print $5}' | cut -d '.' -f 4 > ip_sub.txt

Create list of possible hosts (list from 1-255):

python -c 'for i in range(255): print i+1' > ip_all.txt

Sort files to prepare for diff (could have done this earlier):

cat ip_all.txt | sort -n > ip_all_sort.txt
cat ip_sub.txt | sort -n > ip_sub_sort.txt

Create diff file in columns:

diff -y ip_all_sort.txt ip_sub_sort.txt > ip_sub_all_diff.txt

Now, count how many unused IP addresses:

grep '<' -o ip_sub_all_diff.txt | wc -l

Start with installing nmap to python.

pip install python-nmap

usage looks like this:

import nmap

nm = nmap.PortScanner() 
nm.scan('10.0.0.1')
res = nm.all_hosts()
print res

This way you can skip the whole writing to text files part. res contains your information you can use regex for the grep part, iterate over the results with your for loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM