Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python程序中的Bash_Python_Linux_Bash - Fatal编程技术网

python程序中的Bash

python程序中的Bash,python,linux,bash,Python,Linux,Bash,如何在python中使用bash命令,例如: # ifconfig eth0 promisc 代码如下: import socket # the public network interface HOST = socket.gethostbyname(socket.gethostname()) # create a raw socket and bind it to the public interface s = socket.socket(socket.AF_INET, socket.SO

如何在python中使用bash命令,例如:

# ifconfig eth0 promisc
代码如下:

import socket
# the public network interface
HOST = socket.gethostbyname(socket.gethostname())
# create a raw socket and bind it to the public interface
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
s.bind((HOST, 0))
# Include IP headers
s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
# receive all packages
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
# receive a package
print s.recvfrom(65565)
# disabled promiscuous mode
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)
而不是
s.ioctl
,因为linux不支持此命令

import subprocess
subprocess.check_call(['ifconfig', 'eth0', 'promisc'])

如果希望它从命令返回文本,请使用
check_output
。如果命令失败,两者都会自动引发异常。

@PadraicCunningham:我希望我们不要忽视返回代码<默认情况下应始终使用code>check_call,除非存在忽略故障的特定原因。如果
socket.ioctl
不可用,请研究使用
fcntl.ioctl
而不是使用
ifconfig
。(或者优先使用它而不是
socket.ioctl
)如果您特别想要
bash
功能,比如通配符扩展,那么使用shell选项:
subprocess.check_call(“ls*”,shell=True)
@Flimm:可能,但是
ls*
是一个坏例子,因为它鼓励人们不要使用更好的工具,比如
os.listdir()
。在任何情况下,通配符都与OP的用例无关。