转自:https://www.pinlue.com/article/2021/08/1000/0011676682400.html
python操作nmap
1.简单的小案例
创建PortScanner实例,然后扫描114.114.114.114这个IP的20-443端口。
import nmap
nm = nmap.PortScanner()
ret = nm.scan(‘114.114.114.114’,‘20’)
print ret
返回格式如下:
{
‘nmap’: {
‘scanstats’: {‘uphosts’: ‘1’, ‘timestr’: ‘Tue Oct 25 11:30:47 2016’, ‘downhosts’: ‘0’, ‘totalhosts’: ‘1’, ‘elapsed’: ‘1.11’},
‘scaninfo’: {‘tcp’: {‘services’: ‘20’, ‘method’: ‘connect’}},
‘command_line’: ‘nmap -oX - -p 20 -sV 115.239.210.26’
},
‘scan’: {
‘115.239.210.26’: {
‘status’: {‘state’: ‘up’, ‘reason’: ‘syn-ack’},
‘hostnames’: [{‘type’: ‘’, ‘name’: ‘’}],
‘vendor’: {},
‘addresses’: {‘ipv4’: ‘115.239.210.26’},
‘tcp’: {20: {‘product’: ‘’, ‘state’: ‘filtered’, ‘version’: ‘’, ‘name’: ‘ftp-data’, ‘conf’: ‘3’, ‘extrainfo’: ‘’, ‘reason’: ‘no-response’, ‘cpe’: ‘’}
}
}
}
}
2.内置方法:
还可以打印出简单的信息
import nmap
nm = nmap.PortScanner()
print nm.scaninfo()
{u’tcp’: {‘services’: u’20-443’, ‘method’: u’syn’}}
print nm.command_line()
u’nmap -oX - -p 20-443 -sV 114.114.114.114’
查看有多少个host
print nm.all_hosts()
[u’114.114.114.114’]
查看该host的详细信息
nm[‘114.114.114.114’]
查看该host包含的所有协议
nm[‘114.114.114.114’].all_protocols()
查看该host的哪些端口提供了tcp协议
nm[‘114.114.114.114’][‘tcp’]
nm[‘114.114.114.114’][‘tcp’].keys()
查看该端口是否提供了tcp协议
nm[‘114.114.114.114’].has_tcp(21)
还可以像这样设置nmap执行的参数
nm.scan(hosts=‘192.168.1.0/24’, arguments=’-n -sP -PE -PA21,23,80,3389’