【发布时间】:2020-06-11 15:38:30
【问题描述】:
在学习 Udemy 课程后,我一直在尝试制作一个程序,该程序使用 ifconfig 命令自动更改 Linux 中接口的 mac 地址,并带有 subprocess 和 optparse 模块。
我的问题是关于我在下面的 get_arguments() 函数中的 elif 语句。 我想要这样,如果程序在没有指定参数的情况下在命令行上运行,那么用户将被要求输入 interface 和 new_mac 变量。
下面写的 get_arguments() 函数,
elif not options.interface:
parser.error("[-] Please specify an interface. Use -- help for more info.")
将被执行,打印文本并使用 parser.error() 停止程序, 如果在命令行上运行程序时没有指定参数,甚至不需要输入。
但是,这样写,
if options.interface or options.new_mac:
if not options.interface:
parser.error("[-] Please specify an interface. Use -- help for more info.")
if not options.new_mac:
parser.error("[-] Please specify a new MAC address. Use --help for more info.")
else:
return options
程序将停止获取输入,一切都会好起来的。
这是程序:
#!/usr/bin/env python
import subprocess
import optparse
def get_arguments():
parser = optparse.OptionParser()
parser.add_option("-i", "--interface", dest="interface", help="Interface to change MAC address")
parser.add_option("-m", "--mac", dest="new_mac", help="New MAC address")
(options, arguments) = parser.parse_args()
if not options.interface and options.new_mac:
options = False
return options
elif not options.interface:
parser.error("[-] Please specify an interface. Use -- help for more info.")
elif not options.new_mac:
parser.error("[-] Please specify a new MAC address. Use --help for more info.")
else:
return options
def change_mac(interface, new_mac):
print("[+] Changing MAC address for '" + interface + "' to '" + new_mac + "'")
subprocess.call(["sudo", "ifconfig", interface, "down"])
subprocess.call(["sudo", "ifconfig", interface, "hw", "ether", new_mac])
subprocess.call(["sudo", "ifconfig", interface, "up"])
subprocess.call(["sudo", "ifconfig", interface])
print("[+] Done!")
options = get_arguments()
if not options:
interface = raw_input("Specify interface > ")
new_mac = raw_input("Specify new MAC address > ")
change_mac(interface, new_mac)
else:
change_mac(options.interface, options.new_mac)
【问题讨论】:
-
如果
if语句解析为True,python 不可能转到elif语句,所以问题应该是为什么我的 if 语句解析为 False?总是试图在程序之前责怪程序员,因为他们更有可能失败,这将帮助你调试。 -
你知道
if not A and B和if not (A and B)不一样吧? -
哦,我不知道那两个是不同的。
-
...我现在明白了。谢谢你们的帮助!
标签: python subprocess optparse