Python 调用 Nmap 批量检测端口开放情况

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/10/7 20:21
# @Author : BLKStone
# @Site :
# @File : nmap_port_validation.py.py
# @Software: PyCharm Community Edition
import nmap
# telnet 默认端口 23
# 文档资料
# https://bitbucket.org/xael/python-nmap/src/401642a51919?at=default
# https://bitbucket.org/xael/python-nmap/src/401642a51919e67d2cd9dd0e6ac1ee45f25b1307/example.py?at=default&fileviewer=file-view-default
def make_nmap_ip_input(target_list):
ip_input=''
for ele in target_list:
ip_input = ip_input + str(ele) + ' '
return ip_input[:-1]
# 仅存储开放端口的IP
def only_open_result():
target_ips_file_path="simple_F420_list.txt"
output_file_name='http2.txt'
port = '80'
target_list = []
with open(target_ips_file_path,'r') as f:
for line in f.readlines():
target_ip = line[:-1]
target_list.append(target_ip)
f.close()
print 'scan_target:'
print target_list
nm = nmap.PortScanner()
nm.scan(hosts=make_nmap_ip_input(target_list), ports=port)
print nm.command_line()
print 'all hosts:'
print nm.all_hosts() # get all hosts that were scanned
with open(output_file_name,'w') as telnet_file:
for host in nm.all_hosts():
print('----------------------------------------------------')
print host
lport = nm[host]['tcp'].keys()
lport.sort()
for port in lport:
print('port : %s\tstate : %s' % (port, nm[host]['tcp'][port]['state']))
if nm[host]['tcp'][port]['state'] == 'open':
telnet_file.write(host + '\n')
print('----------------------------------------------------')
telnet_file.close()
# 存储所有IP的端口开放状况
def all_state_show():
target_ips_file_path="simple_F420_list.txt"
output_file_name='http.txt'
port = '80'
target_list = []
with open(target_ips_file_path,'r') as f:
for line in f.readlines():
target_ip = line[:-1]
target_list.append(target_ip)
f.close()
print 'scan_target:'
print target_list
nm = nmap.PortScanner()
nm.scan(hosts=make_nmap_ip_input(target_list), ports=port)
print nm.command_line()
print 'all hosts:'
print nm.all_hosts() # get all hosts that were scanned
with open(output_file_name,'w') as telnet_file:
for host in nm.all_hosts():
print('----------------------------------------------------')
print host
lport = nm[host]['tcp'].keys()
lport.sort()
for port in lport:
print('port : %s\tstate : %s' % (port, nm[host]['tcp'][port]['state']))
telnet_file.write(host + ' ' + str(port) + ' ' + nm[host]['tcp'][port]['state'] + '\n')
print('----------------------------------------------------')
telnet_file.close()
if __name__ == '__main__':
only_open_result()