python中getopt模块

在日常的工作中免不了需要编写很多python脚本,当脚本的功能比较多的时候,又或者需要外部传入参数的时候,如果以参数
名和参数值的方式执行可能脚本显得更直观,也给自己提供方便。

python下有一个getopt的模块,该模块就是处理命令行参数的。

函数getopt(args,shortopts,longopts = [])

args一般是sys.argv[1:]

shortopys 短格式(-)

longopts 长格式(–) //两个杠

执行方法:

python run_cmd.py  -f  iplist.txt -c ifconfig

python run_cmd.py  –file iplist.txt –command ifconfig
代码如下:

 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

 

posted on 2015-02-02 15:41  强者无惧  阅读(703)  评论(0编辑  收藏  举报

导航