Python编写MAC地址修改脚本报'str' object is not callable错误求助
报错根因
optparse解析参数返回的options对象中,new_interface是存储你输入的网卡参数的字符串类型属性,你错误添加了括号将其作为函数调用,触发了'str' object is not callable异常。
同时你的代码还存在另外两处会导致运行失败的隐性问题:
- 调用
mac_changer函数时,错误传入了不存在的options.interface属性,你配置参数时设置的dest值为new_interface,应该取options.new_interface的值 - 拼接
ifconfig命令时没有预留空格,会生成ifconfigeth0 down这类非法命令导致执行失败,且使用shell=True存在安全隐患,推荐用列表形式传参调用命令
修复后完整代码
import subprocess import optparse def mac_changer(interface, mac_add): subprocess.call(["ifconfig", interface, "down"]) subprocess.call(["ifconfig", interface, "hw", "ether", mac_add]) subprocess.call(["ifconfig", interface, "up"]) def get_args(): parser = optparse.OptionParser() parser.add_option("-i", "--interface", dest="new_interface", help="Selects Interface") parser.add_option("-m", "--MAC", dest="new_mac", help="Changes the Mac Address") (options, arguments) = parser.parse_args() # 去掉多余的调用括号 if not options.new_interface: parser.error("No interface specified") elif not options.new_mac: parser.error("No Mac address found in command line") return options options = get_args() # 修正传入的接口参数属性名 mac_changer(options.new_interface, options.new_mac)
内容的提问来源于stack exchange,提问作者Abhiram Sharma
相关产品推荐
相关产品推荐

