在平常的工做中免不了須要編寫不少python腳本,當腳本的功能比較多的時候,又或者須要外部傳入參數的時候,若是以參數
名和參數值的方式執行可能腳本顯得更直觀,也給本身提供方便。python
python下有一個getopt的模塊,該模塊就是處理命令行參數的。session
函數getopt(args,shortopts,longopts = [])app
args通常是sys.argv[1:]ssh
shortopys 短格式(-)函數
longopts 長格式(–) //兩個槓spa
執行方法:命令行
python run_cmd.py -f iplist.txt -c ifconfigcode
python run_cmd.py –file iplist.txt –command ifconfig
代碼以下:blog
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 4 import ConfigParser 5 import paramiko 6 import sys 7 import os 8 import datetime 9 from multiprocessing import Process 10 11 class remote_connection: 12 13 def __init__(self,files,cmd): 14 self.ini = 'iplist.ini' 15 self.allfile = [] 16 17 # 讀取INI配置文件 18 def getini(self): 19 if os.path.isfile(self.ini): 20 pass 21 else: 22 sys.exit('Check your %s exists' % self.ini) 23 cfg = ConfigParser.ConfigParser() 24 cfg.read(self.ini) 25 sec = ''.join(cfg.sections()) 26 options = cfg.options(sec) 27 self.user = cfg.get(sec,options[0]) 28 self.passwd = cfg.get(sec,options[1]) 29 self.host_all = cfg.get(sec,options[2]) 30 self.host = ''.join(self.host_all).split(',') 31 32 # 執行遠程ssh命令 33 def sshcmd(self,host='',port='',username='',passwd=''): 34 s=paramiko.SSHClient() 35 s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 36 try: 37 s.connect(host,port,username,passwd,timeout=5) 38 except Exception: 39 sys.exit(host+'\x1b[1;31m\t\t[鏈接失敗]\x1b[0m') 40 chan = s.get_transport().open_session() 41 chan.exec_command(cmd) 42 status = chan.recv_exit_status() 43 if status == 0: 44 print host+'\x1b[1;32m\t\t[執行成功]\x1b[0m' 45 else: 46 print host+'\x1b[1;31m\t\t[執行失敗]\x1b[0m' 47 48 if __name__ == '__main__': 49 try: 50 opts,args = opts,args = getopt.getopt(sys.argv[1:],"(hH)f:c:",["help","file=","command="]) 51 if len(sys.argv) == 1: 52 print '用法: python xxx.py -f xxx.file -c ifconfig' 53 sys.exit() 54 if sys.argv[1] in ("-h","-H","--help"): 55 print '用法: python xxx.py -f xxx.file -c ifconfig' 56 elif sys.argv[1] in ("-f","--file"): 57 for opt,arg in opts: 58 if opt in ("-f","--file"): 59 files = arg 60 if opt in ("-c","--command"): 61 cmd = arg 62 63 box = [] 64 p = remote_connection(sys.argv[1],sys.argv[2]) 65 p.getini() 66 for i in p.host: 67 box.append(Process(target=p.sshcmd,args=(i,3389,p.user,p.passwd))) 68 for i in box: 69 i.start() 70 i.join() 71 except Exception,e: 72 print e