代码为多线程ping扫描
用法
LM-SHC-16507783:small_script_for_operation yzhu10$ python3 mp_ping.py --help
usage: mp_ping.py [-h] [-mc multiprocessing_count] [-n network]
ping scan for the specific network via the multi-processing,list the
active/inactive hosts
optional arguments:
-h, --help show this help message and exit
-mc multiprocessing_count
define how many ping precess will be execute one time
-n network the network that need to scan
代码:
可以将active IP保存到一个文件中。
#!/usr/bin/env python3
# ping scan for a network
import argparse
from datetime import datetime
import netaddr
import os
import re
from multiprocessing.pool import ThreadPool
from multiprocessing import Pool as processpool
import sys
def ping(ipaddress):
print('ping %s'%ipaddress)
ping_output=os.popen('ping -c 2 %s'%ipaddress).read()
# print(ping_output)
receive_count=re.findall('(\d)\s\w*\s*received',ping_output)
# print(receive_count)
if receive_count != ['0']:
return ['active']
else:
return ['inactive']
usage = '''
how to run this file:
./mp_ping -mc <multiprocessing_count> -n <network>
'''
parser = argparse.ArgumentParser(
description='ping scan for the specific network via the multi-processing,list the active/inactive hosts')
parser.add_argument('-mc', metavar='multiprocessing_count',
help='define how many ping precess will be execute one time')
parser.add_argument('-n', metavar='network',
help='the network that need to scan')
args = parser.parse_args()
if args.mc:
multiprocessing_count = args.mc
if args.n:
network = args.n
else:
print(parser.format_usage())
print(usage)
exit()
# start_time=datetime.now()
pool = ThreadPool(processes=int(multiprocessing_count))
# pool = processpool(processes=int(multiprocessing_count))
net = netaddr.IPNetwork(str(network))
results_obj_dict ={}
# for i in net:
# result_dict.update(ping(str(i)))
# print(result_dict)
for ip in net:
result_obj = pool.apply_async(ping,(str(ip),))
results_obj_dict[str(ip)] = result_obj
pool.close()
pool.join()
active_ip=[]
inactive_ip=[]
for ip,obj in results_obj_dict.items():
if obj.get() == ['active']:
active_ip.append(ip)
print('='*80)
print('active ip: ' + str(active_ip))
# end_time=datetime.now()
# print('script execution tooks %s'%(end_time-start_time))
print('='*80)
record_to_file=input('do you want to record ip in the file y/n: ')
if record_to_file == 'y':
file = open('active_ip_list', 'w+')
file.write('active ip:' + '\n')
for ip in active_ip:
file.write(ip)
file.write('\n')
print('recording completed, please check the file active_ip_list,exit the script')
sys.exit(0)
if record_to_file == 'n':
print('exit the script')
sys.exit(0)