python使用nmap端口扫描的两种方法

第一版:只支持以逗号分隔的端口,不支持端口范围

firstly: sudo apt-get install nmap

secondly:pip install python-nmap

thirdly:copy the code bellow to a file like scan_network.py

#!/usr/bin/env python
import nmap
import optparse
def nmapscan(tgthost,tgtport):
nmscan = nmap.portscanner()
nmscan.scan(tgthost,tgtport)
state=nmscan[tgthost][‘tcp’][int(tgtport)][‘state’]
print (“[*] ” + tgthost + ” tcp/”+tgtport +” “+state)
def main():
parser = optparse.optionparser(‘usage %prog ‘+\
‘-h -p ‘)
parser.add_option(‘-h’, dest=’tgthost’, type=’string’,\
help=’specify target host’)
parser.add_option(‘-p’, dest=’tgtport’, type=’string’,\
help=’specify target port[s] separated by comma’)
(options, args) = parser.parse_args()
tgthost = options.tgthost
tgtports = str(options.tgtport).split(‘,’)
if (tgthost == none) | (tgtports[0] == none):
print (parser.usage)
exit(0)
for tgtport in tgtports:
nmapscan(tgthost, tgtport)
if name == ‘main’:
main

forthly:chmod +x scan_network.py

fifthly: ./scan_network.py -h 192.168.1.1 -p 22,23

第二版:支持以逗号分割及以-分割的端口范围

#!/usr/bin/env python
import nmap
import optparse
def nmapscan(tgthost,tgtport):
nmscan = nmap.portscanner()
nmscan.scan(tgthost,tgtport)
state=nmscan[tgthost][‘tcp’][int(tgtport)][‘state’]
print (“[*] ” + tgthost + ” tcp/”+tgtport +” “+state)
def main():
parser = optparse.optionparser(‘usage %prog ‘+\
‘-h -p ‘)
parser.add_option(‘-h’, dest=’tgthost’, type=’string’,\
help=’specify target host’)
parser.add_option(‘-p’, dest=’tgtport’, type=’string’,\
help=’specify target port[s] separated by comma’)
(options, args) = parser.parse_args()
tgthost = options.tgthost
######this code bellow is to support scan port range like 66-88
tgtports = []
tgtports_cache = str(options.tgtport).split(‘,’)
i = int(len(tgtports_cache))
for m in range( 0,i ):
tgtports_split = str(tgtports_cache[m]).split(‘-‘)
if(len(tgtports_split) < 2): tgtports.extend(tgtports_split) #print(tgtports) else: for n in range(int(tgtports_split[0]),int(tgtports_split[1])+1): tgtports.append(str(n)) #print(tgtports) ######above the tgtports are the ports list you want to scann #tgtports = str(options.tgtport).split(',') if (tgthost == none) | (tgtports[0] == none): print (parser.usage) exit(0) for tgtport in tgtports: nmapscan(tgthost, tgtport) if name == 'main': main()

以上就是python使用nmap端口扫描的两种方法的详细内容,更多请关注 第一php社区 其它相关文章!

Posted in 未分类