在linux系统中运行某些系统命令时,这些命令可以通过增加不同参数实现不同功能, 例如典型的nmap命令,就可以通过组合不同参数实现扫描结果,设想下如果我们写的脚本也能支持根据选择的不同参数来实现不同的运行结果,是不是显得非常专业化,所以今天我们就来看一段代码,看如何实现带命令行参数的脚本,按惯例,我们先看代码:
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 |
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() |
脚本用到了subprocess和optparse,前者可以调用系统命令,后者就是来实现如何自定义参数来执行脚本,shell命令的部分比较简单,在此不在讲了,接下来runBash()函数是返回命令执行结果的,这里大家[……]