在学习书中 netcat 代码的时候,发现其命令行选项和参数的处理存在一些小问题,由于调用 getopt 模块的 getopt() 函数时参数设置不当,会引起代码执行时获取不到参数值或引发异常。该问题在 Python2.7 和 Python3.6 版本都存在。虽然对脚本功能来说无关紧要,但是其代码会对初学者造成一定困扰,所以我简单调试了下代码,修改成正确的方式,也是对 Python 命令行选项和参数处理的一次学习。
问题代码
netcat 脚本通过调用 getopt 模块的 getopt() 函数对命令行选项和参数进行解析,并在 usage() 函数里说明了脚本功能和参数传递。
原代码如下:
def usage ():
......
print "-l --listen - listen on [host]:[port] for incoming connections"
print "-e --execute=file_to_run - execute the given file upon receiving a connection"
print "-c --command - initialize a command shell"
print "-u --upload=destination - upon receiving a connection upload a file and write to [destination]"
print "bhpnet.py -t 192.168.0.1 -p 5555 -l -u=C:\\target.exe"
print "bhpnet.py -t 192.168.0.1 -p 5555 -l -e=\"cat /etc/passwd\""
.....
sys.exit(0)
......
# read the commandline options
try:
opts, args = getopt.getopt(sys.argv[1:],"hle:t:p:c:u:",["help","listen","execute","target","port","command","upload"])
except getopt.GetoptError as err:
print str(err)
usage()
for o,a in opts:
if o in ("-h", "--help"):
usage()
elif o in (