os.system("ifconfig ge1 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'")
will not return to you IP address instead EXIT STATUS code, so you need to use a module that gets you the IP address of your interface(eth0, WLAN0..etc),
As suggested by the @stark link comment, use netifaces package or socket module, examples taken from this post :
import netifaces as ni
ni.ifaddresses('eth0')
ip = ni.ifaddresses('eth0')[2][0]['addr']
print ip
===========================================================================
import socket
import fcntl
import struct
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
get_ip_address('eth0')
EDIT-1:
It is recommended that you run your terminal commands through subprocess rather than os.system as I've read it's a lot more safer.
Now, if you wan to pass the result of ip_address into your ping
command, here we go:
import subprocess
import socket
import fcntl
import struct
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
hostname = "8.8.8.8"
cmdping = "ping -c 1 " + hostname + " -I " + get_ip_address('eth0')
p = subprocess.Popen(cmdping, shell=True, stderr=subprocess.PIPE)
#The following while loop is meant to get you the output in real time, not to wait for the process to finish until then print the output.
while True:
out = p.stderr.read(1)
if out == '' and p.poll() != None:
break
if out != '':
sys.stdout.write(out)
sys.stdout.flush()