0

How can i use a bash command in python for example :

# ifconfig eth0 promisc

in code like :

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)

instead of s.ioctl because linux doesn't support this command ?

przelacz
  • 23
  • 2
  • 7
  • @PadraicCunningham: I'd prefer we didn't promote neglect of return codes. `check_call` should always be used by default unless there is a specific reason why failures should be ignored. – John Zwinck Oct 14 '14 at 13:13
  • Look into using `fcntl.ioctl` instead of shelling out to `ifconfig` if `socket.ioctl` is not available. (Or use it in preference to `socket.ioctl`.) – chepner Oct 14 '14 at 15:00

1 Answers1

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

Or use check_output if you want it to return the text from the command. Either will automatically raise an exception if the command fails.

John Zwinck
  • 207,363
  • 31
  • 261
  • 371
  • 1
    If you specifically want `bash` features like wildcard expansion, then use the shell option: `subprocess.check_call("ls *", shell=True)` – Flimm Oct 14 '14 at 13:15
  • 2
    @Flimm: maybe, but `ls *` is a bad example because it encourages people to not use better tools like `os.listdir()`. In any case wildcarding is not relevant to the OP's use case. – John Zwinck Oct 14 '14 at 13:17