带有arg解析器的Python端口扫描程序无法正确获取多个参数

时间:2015-04-25 01:26:10

标签: python-2.7 argparse

我正在尝试更新一些名为“Violent Python”的好书。许多示例使用了弃用的optparse库,我在MOST示例中很容易切换到argparse,但是,如果我使用多个端口参数,我的修改后的代码不适用于此特定脚本。我变得非常沮丧,我试图使用原始示例,但该代码无法正常工作。

什么有用......

python portScan.py -H ipaddress -p 21

[+] Scan results for: (banner)
[-]21/tcp closed for port

什么不起作用......

python portScan.py -H ipaddress -p 21, 22

usage: usage%prog -H  <target host> -p <target port> [-h] [-H TGTHOST]
                                                 [-p [TGTPORT [TGTPORT ...]]]
usage%prog -H  <target host> -p <target port>: error: argument -p/--tgtPort:   invalid int value: '21,'

我意识到这是因为argparse为一个参数获取多个值并将它们转换为列表,但我尝试了多种方法将列表映射为整数值。他们都失败了。

以下是我的代码......

import argparse
from socket import *
from threading import *

screenLock = Semaphore(value=1)
def connScan(tgtHost, tgtPort):
    try:
        connSkt = socket(AF_INET, SOCK_STREAM)
        connSkt.connect((tgtHost, tgtPort))
        connSkt.send('ViolentPython\r\n')
        results = connSkt.recv(100)
        screenLock.acquire()
        print '[+]%d/tcp open for port '% tgtPort #+ str(tgtPort)
        print '[+] ' + str(results)
    except:
        screenLock.acquire()
        print '[-]%d/tcp closed for port '% tgtPort #+ str(tgtPort)
    finally:
        screenLock.release()
        connSkt.close()
def portScan(tgtHost, tgtPorts):
    try:
        tgtIP = gethostbyname(tgtHost)
    except:
        print "[-] Cannot resolve '%s': Unknown host"%tgtHost
        return
    try:
        tgtName = gethostbyaddr(tgtIP)
        print '\n[+] Scan results for: ' + tgtName[0]
    except:
        print '\n[+] Scan Results for: ' + tgtIP
        setdefaulttimeout(1)
    for tgtPort in tgtPorts:
        t = Thread(target=connScan, args=(tgtHost, tgtPort))
        t.start() 
def main():
    parser = argparse.ArgumentParser("usage%prog " "-H  <target host> -p <target port>")
    parser.add_argument('-H', '--tgtHost', help='specify target host')
    parser.add_argument('-p', '--tgtPort', nargs= '*', type=int, help='specify target port')
    args = parser.parse_args()
    tgtHost = args.tgtHost
    tgtPorts = args.tgtPort #str(args.tgtPort).split(',')
    if (tgtHost == None) | (tgtPorts == None):
        print parser.usage
        exit(0)
    portScan(tgtHost, tgtPorts)
if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:0)

我已经尝试过您的代码了。您知道大部分时间我们都不会使用,来分隔arg值。相反,我们使用空间:

>python port_scanner.py -H 127.0.0.1 -p 21 22

[+] Scan results for: localhost
[-]21/tcp closed for port
[-]22/tcp closed for port