2017-09-02 67 views
0

我正在研究一個簡單的portscanner,並且我希望我的程序在由命令shell執行時採用兩個選項。一般來說,它只能從shell執行,因爲程序絕對需要這些選項。optparse不會收集傳遞給選項的所有值

我想要的選項是:

-H:主機的IP地址

-p:應該被掃描

這裏所有端口的列表是我的問題:我想要的端口

D:\LocalUser\MyPython\Portscanner>C:\Users\LocalUser\AppData\Local\Programs\Pytho n\Python35-32\python.exe portscanner_v0.0.py -H 192.168.1.1 -p 21, 1720, 8000

:由逗號和空白在開始我的程序的本實施例中分離時,像

不幸的是,他們似乎並沒有被我的程序收集,只有第二個選項的第一個值被讀取到我的代碼中的變量中。我正在使用optparse和Python 3.5,請告訴我如何從shell中獲取所有端口。

這裏是我的代碼:

def portScan(tgtHost, tgtPorts): 
    #doing my port scans 
    #wont show my actual code here, it's working fine 


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='string', help='specify target port[s] separated by comma') 
    (options, args) = parser.parse_args() 
    tgtHost = options.tgtHost 
    tgtPorts = str(options.tgtPort).split(', ') 
    if ((tgtHost == None) | (tgtPorts[0]==None)): 
     print(parser.usage) 
     exit(0) 
    portScan(tgtHost, tgtPorts) 

if __name__ == "__main__": 
    main() 

回答

1

參數數量已經由空格分割,所以你需要使用

tgtPorts = str(options.tgtPort).split(',') 

,並把它作爲python.exe portscanner_v0.0.py -H 192.168.1.1 -p 21,1720,8000

還要注意的是, optparse模塊is deprecated since Python 2.7並替換爲argparse

+0

工作正常,謝謝!有沒有辦法使用空間(只是問...)? –