Optparse - 如何在 Port Scanner 中解析多个端口(暴力 Python)

Optparse - how to parse multiple port in Port Scanner (Violent Python)

我正尝试从 Violent Python 和我 运行 进行端口扫描,遇到以下问题。此 post 将类似于此 post ("") 但这是一个不同的问题。我想 运行 像这样的多个端口

python PortScanner.py -H www.google.com -p 21, 22, 80

但它只扫描了最初的第一个端口 (21) 然后退出了程序所以我想知道如何将此代码修复到 运行 多个端口。

注意:它还说 Pylance 无法访问 (option, args) = parser.parse_args() 中的 args,所以它是否与它有关,或者我该如何修复它。

import optparse
import socket
from socket import *
def connscan(tgtHost,tgtPorts):
    try:
        connSkt= socket(AF_INET,SOCK_STREAM)
        connSkt.connect((tgtHost, tgtPorts))
        connSkt.send('Violent Python\r\n')
        results = connSkt.recv(100)
        print ('[+]%d/tcp open'% tgtPorts)
        print ('[+]' + str(results))
        connSkt.close()
    except: 
        print ('[-]%d/tcp closed'% tgtPorts)

def PortScan(tgtHost,tgtPorts):
    try:
        tgtIP=gethostbyname(tgtHost)
    except:
        print ("[-] Cannot resolve '%s': Unkown host"%tgtHost)
        return
    try:
        tgtName= gethostbyaddr(tgtIP)
        print ("\n[+] Scan Result for:   "+ tgtName[0])
    except:
        print ("\n[+] Scan Result for: " + tgtIP)
        setdefaulttimeout(1)
        for tgtPort in tgtPorts:
            print ("Scanning Port " + tgtPort)
            connscan(tgtHost,int(tgtPort))

def main():

    parser = optparse.OptionParser('Usage: %prog -H ' +\
    '<target host> -p <target port>')
    parser.add_option('-H', dest = 'tgtHost', type = 'string', \
    help = 'specify target host')
    parser.add_option('-p', dest = 'tgtPort', type = 'int', \
    help = 'Specify target port' )
    (options,args) = parser.parse_args()
    tgtHost = options.tgtHost
    tgtPorts = str(options.tgtPort).split(',')
    
    if ( tgtHost == None) | (tgtPorts[0] == None):
        print(parser.usage)
        exit (0)
    print(*tgtPorts, sep=", ")
    PortScan(tgtHost,tgtPorts)

if __name__ == '__main__':
    main()

我通过将 tgtPort 的类型从 int 更改为 string 并在命令行 python PortScanner.py -H www.google.com -p "21, 22, 80".