import optparse
import re
from nmap import nmap
def Nmapscan(targetIP):
# 实例化PortScanner对象
nm = nmap.PortScanner()
try:
# hosts为目标ip地址,argusments为nmap的扫描参数
# -sn:使用ping进行扫描
# -PE:使用ICMP的echo请求包
result = nm.scan(hosts=targetIP, arguments='-sn -PE')
# 对请求的结果进行切片处理
state = result['scan'][targetIP]['status']['state']
print(f'[{targetIP}] is [{state}]')
except Exception:
pass
if __name__ == '__main__':
parse_arg = optparse.OptionParser(
"Usage:%prog -i ip\n\n" 'Example: python %prog --icmp 192.168.1.1/192.168.1.1-100\n\n')
# 添加目标IP参数 -i
parse_arg.add_option('-i', '--icmp', dest='targetIP', default='192.168.1.1', type='string')
options, args = parse_arg.parse_args()
# 判断主机是多台还是单台
res = '[-]+\d'
if re.findall(res, options.targetIP):
if options.targetIP.count('-') == 2:
for j in range(int(options.targetIP.split('.')[2].split('-')[0]),
int(options.targetIP.split('.')[2].split('-')[1]) + 1):
for k in range(int(options.targetIP.split('.')[3].split('-')[0]),
int(options.targetIP.split('.')[3].split('-')[1]) + 1):
Nmapscan(options.targetIP.split('.')[0] + '.' + options.targetIP.split('.')[1] + '.' + str(
j) + '.' + str(k))
elif '-' in options.targetIP.split('.').pop(-2) and options.targetIP.count('-') == 1:
for y in range(int(options.targetIP.split('.')[2].split('-')[0]),
int(options.targetIP.split('.')[2].split('-')[1]) + 1):
Nmapscan(options.targetIP.split('.')[0] + '.' + options.targetIP.split('.')[1] + '.' + str(y) + '.' +
options.targetIP.split('.')[3])
elif options.targetIP.count('-') == 1:
for x in range(int(options.targetIP.split('-')[0].split('.')[3]),
int(options.targetIP.split('-')[1].split('.')[0]) + 1):
Nmapscan(options.targetIP.split('.')[0] + '.' + options.targetIP.split('.')[1] + '.' +
options.targetIP.split('.')[2] + '.' + str(x))
else:
Nmapscan(options.targetIP)
|