python-nmap是python的一个模块库,使用这个模块可以让python很方便的操作nmap扫描器来工作,它可以帮助管理员完成自动扫描任务和生成报告的工具,它还支持nmap的脚步输出。

坏境准备:

###1、安装python-nmap和yum install nmap

[root@localhost ~]# pip install python-nmap
You are using pip version 7.1.0, however version 9.0.1 is available.
You should consider upgrading via the ‘pip install –upgrade pip’ command.
Collecting python-nmap
Downloading python-nmap-0.6.1.tar.gz (41kB)
100% 45kB 40kBs
Installing collected packages python-nmap
Running setup.py install for python-nmap
Successfully installed python-nmap-0.6.1

具体查看链接:http://xael.org/pages/python-nmap-en.html
[root@localhost ~]# yum install –y nmap

###2、python 脚本代码

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
[root@localhost shell]# cat saomiao.py 
# -*- coding: utf-8 -*-
#!/usr/bin/python
import sys
import nmap

scan_row = [ ]
input_data = raw_input('Please input host and port: ')
scan_row = input_data.split(" ")
if len( scan_row ) !=2:
print "Input errors,example\"192.168.1.0/24 80,443,22\""
sys.exit(0)
hosts = scan_row[0] #接收用户输入的主机
port = scan_row[1] #接收用户输入的端口
try:
nm = nmap.PortScanner() #创建端口扫描对象
except nmap.PortScannerError:
print ('Nmap not found,',sys.exc_info()[0])
sys.exit(0)
try:
nm.scan(hosts=hosts,arguments='-v -sS -p '+port)
except Exception,e:
print "Scan error:"+str(e)
for host in nm.all_hosts():
print('----------------------------------------------------')
print('Host : %s (%s)' % (host, nm[host].hostname()))
print('State : %s' % nm[host].state())
for proto in nm[host].all_protocols():
print('----------')
print('Protocol : %s' % proto)
lport = nm[host][proto].keys()
lport.sort()
for port in lport:
print ('port : %s\tstate : %s' % (port, nm[host][proto][port]['state']))

###3、执行测试
如果执行过程出现报错:
[root@localhost shell]# python nmap.py
Please input host and port: 192.168.1.200 80
Traceback (most recent call last):
File “nmap.py”, line 4, in
import nmap
File “/data/shell/nmap.py”, line 16, in
except nmap.PortScannerError:
AttributeError: ‘module’ object has no attribute ‘PortScannerError’

发现,脚本名称为nmap.py 更改名称后执行正常。

###Port scanning result:

  • 10.6.17.83
    1
    2
    3
    4
    5
    6
    7
    8
    9
    [root@10-6-17-83 shell]# python saomiao.py 
    Please input host and port: 10.6.17.83 1-65535
    ----------------------------------------------------
    Host : 10.6.17.83 (localhost) State : up
    Protocol : tcp port : 3306 state : open
    port : 8022 state : open
    port : 8080 state : open
    port : 10050 state : open
    port : 10051 state : open

Comments

2017-02-14