命令行參數傳遞
python main.py -H 192.168.1.1 -p 22,23,24
#coding:utf-8
import optparse
def PortScan(host,port):
print("針對主機",host,"掃描結束了...")
def main():
Usage = "[*] Usage : main.py -H <host> -p <port>"
parser = optparse.OptionParser(Usage)
parser.add_option('-H', dest='Host', type='string', help='specify target host')
parser.add_option('-p', dest='Port', type='string', help='specify target port[s]')
(options, args) = parser.parse_args()
Host = options.Host
Port = str(options.Port).split(',')
if (Host != "None" and Port[0] != "None"):
print("針對主機{} 執行端口{} 開始掃描...".format(Host,Port))
PortScan(Host,Port)
else:
parser.print_help()
if __name__ == "__main__":
main()
下面這一種適合一個命令參數干多件事.python main.py -a Query 192.168.1.1 192.168.1.2
#coding:utf-8
import optparse
def main():
Usage = "[*] Usage : main.py -a cmd <host1> <host2>"
parser=optparse.OptionParser(Usage)
parser.add_option('-a',dest="QueryHost",help="查詢主機情況.")
(options,args)=parser.parse_args()
if options.QueryHost:
argc = options.QueryHost
QueryHost(argc,args)
else:
parser.print_help()
def QueryHost(argc,args):
print("傳遞參數1:{},傳遞參數2:{}".format(argc,args))
if(argc == "query"):
for i in range(len(args)):
print(args[i])
elif(argc == "add"):
print("增加主機{}".format(args))
if __name__ == '__main__':
main()
我們還可以編寫一個交互式的Shell環境,這樣能更加靈活的操作命令,操作方式 [shell] # ls
# coding:utf-8
import os
def add(x, y):
print("兩數相連",x + y)
def clear():
os.system("cls")
def main():
while True:
try:
cmd = str(input("[Shell] # ")).split()
cmd_len = len(cmd)
if (cmd == ""):
continue
elif (cmd[0] == "exit"):
exit(1)
elif (cmd[0] == "clear"):
clear()
elif (cmd[0] == "add"):
if(cmd_len-1 >= 2):
temp1 = cmd[1]
temp2 = cmd[2]
add(temp1,temp2)
else:
print("add 參數不正確,至少傳遞2個參數")
else:
print("沒有找到這個命令")
except Exception:
continue
if __name__ == '__main__':
main()

如果需要編寫一些相對大型的項目,則需要使用類來開發,以下代碼用類實現的命令行傳遞.
#coding:utf-8
import optparse
class MyClass:
def __init__(self):
usage = '''
$$\ $$\ $$\
$$ | $$ | $$ |
$$ |$$\ $$\ $$$$$$$\ $$$$$$$\ $$$$$$\ $$$$$$\ $$ | $$\
$$ |$$ | $$ |$$ _____|$$ __$$\ \____$$\ $$ __$$\ $$ | $$ |
$$ |$$ | $$ |\$$$$$$\ $$ | $$ | $$$$$$$ |$$ | \__|$$$$$$ /
$$ |$$ | $$ | \____$$\ $$ | $$ |$$ __$$ |$$ | $$ _$$<
$$ |\$$$$$$$ |$$$$$$$ |$$ | $$ |\$$$$$$$ |$$ | $$ | \$$\
\__| \____$$ |\_______/ \__| \__| \_______|\__| \__| \__|
$$\ $$ |
\$$$$$$ |
\______/
'''
parser = optparse.OptionParser(usage=usage)
parser.add_option("-s", "--server", type="string" , dest="server", help="you server IP")
parser.add_option("-p", "--port", type="int", dest="port", help="you server port")
self.options, self.args = parser.parse_args()
parser.print_help()
def check(self):
if not self.options.server or not self.options.port:
exit()
def fuck(self,ip,port):
try:
print("接收到參數列表,准備執行功能!")
for i in range(0,100):
print(ip,port)
except:
print("[ - ] Not Generate !")
if __name__ == '__main__':
opt = MyClass()
opt.check()
ip = opt.options.server
port = opt.options.port
if ip != "None" and port != "None":
opt.fuck(ip,port)

