用于扫描远程HTTP客户端的Python CGI脚本

时间:2014-03-11 19:13:15

标签: python python-2.7 cgi web.py nmap

我在运行这个python web脚本并在网页上打印出结果时遇到了一些麻烦。这是一个小型项目,我将在OpenWRT路由器上运行。

当无线客户端连接到接入点时,CGI脚本将针对从HTTP会话检索到的设备的IP地址运行,并显示是否有任何端口处于打开状态,可能会导致个人遭受某种攻击公共网络。

我可以通过wireshark数据包捕获确认端口扫描是否正常运行。

在那一刻我不断收到CGI错误,说明Nmap语法有错误 - 虽然我知道这可以在Python shell中使用

我得到的错误是 -

A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred.
 /Applications/XAMPP/xamppfiles/cgi-bin/test.py in ()
     20 for client in nm.scan():
     21         print('----------------------------------------------------')
=>   22         print('Host : %i' % (nm[client].all_protocols().keys))
     23 """
     24 
nm = <nmap.nmap.PortScanner object>, client = 'nmap', ].all_protocols undefined
 /Applications/XAMPP/xamppfiles/cgi-bin/build/bdist.macosx-10.8-intel/egg/nmap/nmap.py in __getitem__(self=<nmap.nmap.PortScanner object>, host='nmap')

<type 'exceptions.KeyError'>: 'nmap'
      args = ('nmap',)
      message = 'nmap' 

这是我的代码

#!/usr/bin/env python2.7
import cgi
import os
import nmap
import cgitb; cgitb.enable()  # for troubleshooting

print "Content-type: text/html"
print
print """
<html>
<head><title>Sample CGI Script</title></head>
<body>
<h3> Sample CGI Script </h3>
"""
client = cgi.escape(os.environ["REMOTE_ADDR"])
print ('your IP Address is: ' + client)
nm = nmap.PortScanner()
nm.scan(client, '21')

for client in nm.scan():
    print('----------------------------------------------------')
    print('Host : %i' % (nm[client].all_protocols().keys))
"""

</body> 
</html>
 """

1 个答案:

答案 0 :(得分:0)

#!/usr/bin/env python

""" Nmap CGI """

import cgi
import os
from libnmap.process import NmapProcess
from libnmap.parser import NmapParser

print 'Content-Type: text/html'
print # Blank line marking end of HTTP headers

def main(target):
    """ I'm a lumberjack and i'm ok """
    nmap = NmapProcess(target, options="-T5 -p 21")
    nmap.run()
    nmap_report = NmapParser.parse(nmap.stdout)

    for host in nmap_report.hosts:
        address = host.address
        hostname = host.hostnames[0]
        ports = host.get_ports()
        ports = '<br/>'.join(["Port: %s Proto: %s<br/>" % (_id, name)
                            for (_id, name) in host.get_ports()])

        print """
        <center><hr style='margin-top:5%'>
        Hostname: {hostname} <br/> Address: {address} <br>
        Open ports: {ports}
        <hr>
        </center>
        """.format(address=address, ports=ports, hostname=hostname)

main(cgi.escape(os.environ["REMOTE_ADDR"]))

<强>输出

Content-Type: text/html


        <center><hr style='margin-top:5%'>
        Hostname: localhost <br/> Address: 127.0.0.1 <br>
        Open ports: Port: 21 Proto: tcp<br/>
        <hr>
        </center>