《Python 黑帽子》学习笔记 - 命令行选项和参数处理 - Day 4

本文探讨了《Python 黑帽子》一书中关于命令行选项和参数处理的问题,主要关注getopt模块的使用。通过示例代码,解释了getopt()函数的参数设置以及在处理命令行参数时可能出现的GetoptError异常。文章提醒开发者在编写脚本时需注意参数的正确传递和usage函数的准确描述。
摘要由CSDN通过智能技术生成

在学习书中 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 (
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值