文件未找到错误:[Errno 2] 没有该文件或目录:'ifconfig'

3

我学习了使用subprocess.call修改mac地址的两种方法,第一种方法成功了但是第二种方法出错了,我不理解错误原因。这是我的代码:

#! /usr/bin/python3.5
import subprocess
interface = input("Enter Interface of Your Choice: ")
mac_chg = input("Enter New Mac Address: ")
print("[+]Changing Mac ADDRESS of " + interface + " to " + mac_chg)
subprocess.call(["ifconfig", interface, "down"])
subprocess.call(["ifconfig", interface, "hw", "ether", mac_chg])
subprocess.call(["ifconfig", interface, "up"])

这是错误信息:

Traceback (most recent call last):
  File "/home/kali/PycharmProjects/hello/main.py", line 7, in <module>
    subprocess.call(["ifconfig", interface, "down"])
  File "/usr/lib/python3.8/subprocess.py", line 340, in call
    with Popen(*popenargs, **kwargs) as p:
  File "/usr/lib/python3.8/subprocess.py", line 854, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "/usr/lib/python3.8/subprocess.py", line 1702, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'ifconfig'

Process finished with exit code 1

因为这个错误,我无法继续进行。


请确保使用正确的接口并具有运行ifconfig命令的权限。 - Farhad Sarvari
1个回答

5

在Linux中,默认情况下subprocess.call不使用shell来运行我们的命令,因此您不能使用像cd这样的shell命令。

因此,只需向subprocess.call添加一个参数即shell=True,然后尝试执行。

例如:

subprocess.call(["ifconfig", interface, "down"], shell=True)

1
你关于 cd 的说法是正确的,因为它是一个 shell 内置命令。但是在 Bash 中,ifconfig 不是一个 shell 内置命令。它是一个可执行文件,可以通过 subprocess 模块找到并运行它。我可以轻松调用 subprocess.call(["ifconfig"]) 而不需要传递 shell=True - S.B

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接