扫描子网范围时出错,Python 2.7端口扫描程序

时间:2017-07-19 10:39:03

标签: python python-2.7 sockets

我正在研究这个Python端口扫描程序,我正在尝试实现一个允许此端口扫描程序扫描本地子网的功能。

目前,当目标IP以.0结尾时,它会扫描该子网范围内的每个IP(.1 - .255),除非我运行程序时,为每个IP内的每个IP返回“无法解析,未知主机”子网范围。我目前的代码如下:

# import modules used in port scanner
import optparse
from socket import *
from threading import *
import ipaddress

# connect-scan function, deals with connecting to the host / determining if ports are open / closed, takes arguments tgtHost, tgtPort
def connScan(tgtHost, tgtPort):
    try:
        connSkt = socket(AF_INET, SOCK_STREAM)
        connSkt.connect((tgtHost, tgtPort))
        connSkt.send('\r\n')

        result = connSkt.recv(100)
        # prints result if port is open
        print '[+] ' + str(tgtPort) + '/tcp open'
    except:
        # prints result if port is closed
        print '[-] ' + str(tgtPort) + '/tcp closed'
    finally:
        connSkt.close()

# port-scan function, takes arguments tgtHost, tgtPorts 
def portScan(tgtHost, tgtPorts):
    try:
        # tries to get target IP address
        tgtIP = gethostbyname(tgtHost)
    except:
        # if unsuccesful, prints out following result
        print '[-] cannot resolve ' + unicode(tgtHost) + ': unknown host'
        return

    try:
        # tries to get target address
        tgtName = gethostbyaddr(tgtIP)
        print '\n[+] scan results for: ' + tgtName[0]
    except:
        print '\n[+] scan results for: ' + tgtIP
    # sets default time out to 1
    setdefaulttimeout(1)
    # for every port in tgtPorts
    for tgtPort in tgtPorts:
        # creates thread, target is connScan function, arguments are tgtHost, int(tgtPort)
        t = Thread(target=connScan, args=(tgtHost, int(tgtPort)))
        # starts the thread 
        t.start()

def main():
    parser = optparse.OptionParser('usage %prog -t <target-host> -p <target-port(s)>')
    parser.add_option('-t', dest='tgtHost', type='string', help='specify target host, for local subnet, use 192.168.1.0 (scans range 192.168.1.1 - 192.168.1.255')
    parser.add_option('-p', dest='tgtPort', type='string', help='specify target port(s), seperated by a comma, seperate ranges with a -')
    (options, args) = parser.parse_args()

    if (options.tgtHost == None) | (options.tgtPort == None):
        print parser.usage
        exit(0)
    else:
        tgtHost = options.tgtHost
        if tgtHost.endswith('.0'):
            hosts = ipaddress.ip_network(unicode(tgtHost+'/24'))
        else:
            hosts = [tgtHost]
        # allows ranges of ports to be used, when seperated by a -
        if '-' in str(options.tgtPort):
            tgtPorts = options.tgtPort.split('-')
            tgtPorts = range(int(tgtPorts[0]),int(tgtPorts[1]))
        else:
            tgtPorts = str(options.tgtPort).split(',')
    for tgtHost in hosts:
        portScan(tgtHost, tgtPorts)

if __name__ == '__main__':
    main()

我一直在努力为此找到解决方案,但是已经空了。有谁知道代码有什么问题吗?

0 个答案:

没有答案