In the daily work of the need to write a lot of Python script, when the function of the script is more, or the need for external input parameters, if the parameters
Name and parameter values can be executed in a way that makes the script seem more intuitive and convenient for you.
Python has a getopt module that handles command-line arguments.
function getopt (args,shortopts,longopts = [])
Args are generally sys.argv[1:]
Shortopys short Format (-)
Longopts long Format (–)//two bars
Execution method:
Python run_cmd.py-f iplist.txt-c ifconfig
Python run_cmd.py–file Iplist.txt–command ifconfig
The code is as follows:
1 #!/usr/bin/env python2 #-*-coding:utf-8-*-3 4 ImportConfigparser5 ImportParamiko6 ImportSYS7 ImportOS8 Importdatetime9 fromMultiprocessingImportProcessTen One classremote_connection: A - def __init__(self,files,cmd): -Self.ini ='Iplist.ini' theSelf.allfile = [] - - #Read INI configuration file - defGetini (self): + ifOs.path.isfile (Self.ini): - Pass + Else: ASys.exit ('Check your%s exists'%Self.ini) atCFG =Configparser.configparser () - Cfg.read (Self.ini) -SEC ="'. Join (Cfg.sections ()) -Options =cfg.options (sec) -Self.user =Cfg.get (sec,options[0]) -SELF.PASSWD = Cfg.get (sec,options[1]) inSelf.host_all = Cfg.get (sec,options[2]) -Self.host ="'. Join (Self.host_all). Split (',') to + #execute remote SSH command - defSshcmd (self,host="', port="', username="', passwd="'): thes=Paramiko. Sshclient () * S.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) $ Try:Panax NotoginsengS.connect (host,port,username,passwd,timeout=5) - exceptException: theSys.exit (host+'\x1b[1;31m\t\t[Connection Failed]\x1b[0m') +Chan =S.get_transport (). Open_session () A Chan.exec_command (cmd) theStatus =chan.recv_exit_status () + ifStatus = =0: - Printhost+'\x1b[1;32m\t\t[Successful Execution]\x1b[0m' $ Else: $ Printhost+'\x1b[1;31m\t\t[execution Failure]\x1b[0m' - - if __name__=='__main__': the Try: -Opts,args = Opts,args = Getopt.getopt (sys.argv[1:],"(HH) F:c:",[" Help","file=","command="])Wuyi ifLen (sys.argv) = = 1: the Print 'usage: Python xxx.py-f xxx.file-c ifconfig' - sys.exit () Wu ifSYS.ARGV[1]inch("- H","- H","--help"): - Print 'usage: Python xxx.py-f xxx.file-c ifconfig' About elifSYS.ARGV[1]inch("- F","--file"): $ forOpt,arginchopts: - ifOptinch("- F","--file"): -Files =Arg - ifOptinch("- C","--command"): Acmd =Arg + thebox = [] -p = remote_connection (sys.argv[1],sys.argv[2]) $ P.getini () the forIinchP.host: theBox.append (Process (target=p.sshcmd,args= (i,3389, p.user,p.passwd ))) the forIinchBox: the I.start () - I.join () in exceptexception,e: the PrintE
Python in getopt module