在linux系统中运行某些系统命令时,这些命令可以通过增加不同参数实现不同功能, 例如典型的nmap命令,就可以通过组合不同参数实现扫描结果,设想下如果我们写的脚本也能支持根据选择的不同参数来实现不同的运行结果,是不是显得非常专业化,所以今天我们就来看一段代码,看如何实现带命令行参数的脚本,按惯例,我们先看代码:
import subprocess
import optparse
HOMEDIR_USAGE = """
du -sh $HOME | cut -f1
"""
IPADDR = """
/sbin/ifconfig -a | awk '/(cast)/ { print $2 }' | cut -d':' -f2 | head -1
"""
def runBash(cmd):
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
out = p.stdout.read().strip()
return out #This is the stdout from the shell command
VERBOSE=False
def report(output,cmdtype="UNIX COMMAND:"):
if VERBOSE:
print "%s: %s" % (cmdtype, output)
else:
print output
def controller():
global VERBOSE
p = optparse.OptionParser(description='A unix toolbox',
prog='py4sa',
version='py4sa 0.1',
usage= '%prog [option]')
p.add_option('--ip','-i', action="store_true", help='gets current IP Address')
p.add_option('--usage', '-u', action="store_true", help='gets disk usage of homedir')
p.add_option('--verbose', '-v',
action = 'store_true',
help='prints verbosely',
default=False)
options, arguments = p.parse_args()
if options.verbose:
VERBOSE=True
if options.ip:
value = runBash(IPADDR)
report(value,"IPADDR")
elif options.usage:
value = runBash(HOMEDIR_USAGE)
report(value, "HOMEDIR_USAGE")
else:
p.print_help()
def main():
controller()
if __name__ == '__main__':
main()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
importsubprocess
importoptparse
HOMEDIR_USAGE="""
du -sh $HOME | cut -f1
"""
IPADDR="""
/sbin/ifconfig -a | awk '/(cast)/ { print $2 }' | cut -d':' -f2 | head -1
"""
defrunBash(cmd):
p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE)
out=p.stdout.read().strip()
returnout#This is the stdout from the shell command
VERBOSE=False
defreport(output,cmdtype="UNIX COMMAND:"):
ifVERBOSE:
print"%s: %s"%(cmdtype,output)
else:
printoutput
defcontroller():
globalVERBOSE
p=optparse.OptionParser(description='A unix toolbox',
prog='py4sa',
version='py4sa 0.1',
usage='%prog [option]')
p.add_option('--ip','-i',action="store_true",help='gets current IP Address')
p.add_option('--usage','-u',action="store_true",help='gets disk usage of homedir')
p.add_option('--verbose','-v',
action='store_true',
help='prints verbosely',
default=False)
options,arguments=p.parse_args()
ifoptions.verbose:
VERBOSE=True
ifoptions.ip:
value=runBash(IPADDR)
report(value,"IPADDR")
elifoptions.usage:
value=runBash(HOMEDIR_USAGE)
report(value,"HOMEDIR_USAGE")
else:
p.print_help()
defmain():
controller()
if__name__=='__main__':
main()
脚本用到了subprocess和optparse,前者可以调用系统命令,后者就是来实现如何自定义参数来执行脚本,shell命令的部分比较简单,在此不在讲了,接下来runBash()函数是返回命令执行结果的,这里大家可以看看subprocess模块如何使用,report()函数打印命令的结果值输出,controller()函数就是核心控制我们自定义参数的函数,首先初始化类,p.add_option()方法实现一次增加一个选项,支持长格式和短格式,例如:’–ip’,’-i’, action=”store_true”,是默认动作,表示单独存储;p.parse_args()方法来解析命令行,返回是两部分的元组,其中一个是包含值的实例,另一个是命令行参数列表,接下来就是根据用户选中的参数类型进行不同的结果输出,到此脚本结束,运行结果如下, 有木有高大上的感脚:
Usage: py4sa [option]
A unix toolbox
Options:
--version show program's version number and exit
-h, --help show this help message and exit
-i, --ip gets current IP Address
-u, --usage gets disk usage of homedir
-v, --verbose prints verbosely
1
2
3
4
5
6
7
8
9
10
Usage:py4sa[option]
Aunixtoolbox
Options:
--versionshowprogram'sversionnumberandexit
-h,--helpshowthishelpmessageandexit
-i,--ipgetscurrentIPAddress
-u,--usagegetsdiskusageofhomedir
-v,--verboseprintsverbosely