没有多进程,ping一个网段的IP地址往往要花费几十分钟;使用多进程,几秒钟解决。
import subprocess
import os
def ping(host):
rc = subprocess.call(
'ping -c2 %s &> /dev/null' % host,
shell=True
)
if rc:
print('%s: down' % host)
else:
print('%s: up' % host)
if __name__ == '__main__':
ips = ('192.168.1.%s' % i for i in range(1, 255))
for ip in ips:
pid = os.fork()
if not pid:
ping(ip)
exit()