Python 命令行模块使用技巧

Python
329
0
0
2023-02-12
标签   Python进阶

命令行参数传递

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()

img

如果需要编写一些相对大型的项目,则需要使用类来开发,以下代码用类实现的命令行传递.

#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)

img