名称错误:未定义全局名称'interfaceName',即使它是


def putCardMon():
interfaceName = input(('Type an interface name to put in monitor mode: '))
print(colored('[+] ', 'green') + 'Trying to put the interface ' + colored(interfaceName, 'yellow') + ' in monitor moden')
call(["sudo ifconfig " + interfaceName + " down; sudo iwconfig " + interfaceName + " mode monitor; sudo ifconfig " + interfaceName + " up"], shell=True)
interfaceMonCheck = Popen(["iwconfig " + interfaceName + " | grep Mode | cut -d ':' -f2 | cut -d ' ' -f1"], shell=True, stdout=PIPE, universal_newlines=True).communicate()[0].rstrip()
sleep (1)
---//lots of code before the putCardMon is called//---
interfacesList = Popen("ifconfig -a | grep Link | cut -d ' ' -f1", shell=True, stdout=PIPE, universal_newlines=True).communicate()[0].rstrip()
print('The available interfaces are:n' + interfacesList + 'n')
putCardMon()
print('Checking if ' + interfaceName + ' is really in monitor mode.')
if interfaceMonCheck == 'Managed':
print('The interface ' + colored(interfaceName, "green") + ' is not in monitor mode! Check if you typed the interface name correctly or contact support.n')
putCardMon()
elif interfaceMonCheck == 'Monitor':
print(colored('The interface ' + colored(interfaceName, "green") + ' is in monitor mode!'))
pass
else:
print(colored('There was an unexpected error. Contact support!n', "red"))
exit()

脚本运行良好,函数完成了它的工作,但当它到达检查部分时,一切都会走下坡路。

Traceback (most recent call last):
File "script.py", line 76, in <module>
print('Checking if ' + interfaceName + ' is really in monitor mode.')
NameError: name 'interfaceName' is not defined

如果为其分配字符串的函数已经被调用并成功地为其分配了值,那么interfaceName为什么没有被定义?

我在堆栈溢出中搜索了相同的错误,但所有线程都得到了响应,这要么是缩进错误,要么是函数在调用后定义的,这里的情况都不是这样。我真的别无选择。我什么都试过了。

来自https://python-textbok.readthedocs.io/en/1.0/Variables_and_Scope.html#variable-scope-and-lifetime

函数内部定义的变量是该函数的局部变量作用它可以从定义点访问,直到功能结束

您的变量interfaceName仅在函数putCardMon()的范围内定义。它不再存在于功能范围之外。因此,您得到了错误。

如果要在函数体之外使用变量,请考虑返回并保存其值。

def putCardMon():
interfaceName = input(('Type an interface name to put in monitor mode: '))
print(colored('[+] ', 'green') + 'Trying to put the interface ' + colored(interfaceName, 'yellow') + ' in monitor moden')
call(["sudo ifconfig " + interfaceName + " down; sudo iwconfig " + interfaceName + " mode monitor; sudo ifconfig " + interfaceName + " up"], shell=True)
interfaceMonCheck = Popen(["iwconfig " + interfaceName + " | grep Mode | cut -d ':' -f2 | cut -d ' ' -f1"], shell=True, stdout=PIPE, universal_newlines=True).communicate()[0].rstrip()
sleep (1)
return interfaceName
# Later you can do this
interfaceName = putCardMon()

最新更新