pingnet: Add a script to identify available addresses on a network

master
Dustin C. Hatch 2014-03-13 09:04:15 -05:00
parent 062569a111
commit 0cea591bb6
1 changed files with 37 additions and 0 deletions

37
pingnet.py Executable file
View File

@ -0,0 +1,37 @@
#!/usr/bin/env python3
import ipaddr
import os
import socket
import subprocess
import sys
def main():
for arg in sys.argv[1:]:
try:
net = ipaddr.IPv4Network(arg)
except ipaddr.AddressValueError:
sys.stderr.write('Invalid network address: {}\n'.format(arg))
else:
for ip in net.iterhosts():
p = subprocess.Popen(['ping', '-c1', '-W1', str(ip)],
stdout=open(os.devnull, 'w'),
stderr=open(os.devnull, 'w'),
stdin=open(os.devnull))
try:
p.wait()
except KeyboardInterrupt:
print()
raise SystemExit
try:
hostname = '{} ({})'.format(
ip,
socket.gethostbyaddr(str(ip))[0],
)
except socket.herror:
hostname = ip
state = 'in use' if p.returncode == 0 else 'not responding'
print('{} is {}'.format(hostname, state))
if __name__ == '__main__':
main()