Reputation: 3254
I use ifconfig command with awk to catch system's ip addresses
$ ifconfig | grep -E 'inet.[0-9]' | awk '{ print $2}'
127.0.0.1
192.168.8.2
How to convert o/p into a list using python ?
Upvotes: 0
Views: 7930
Reputation: 339
I just modified the code posted by @Pujan to make it work for linux. (tested in Ubuntu 12.04):
import os
ipa=[]
f=os.popen("/sbin/ifconfig | grep -i \"inet\" | grep -iv \"inet6\" | " + "awk {'print $2'} | sed -ne 's/addr\:/ /p'")
for i in f.readlines():
ipa.append(i.rstrip('\n'))
print ipa
Upvotes: 1
Reputation: 3542
You might just skip shelling out to call a pipeline of commands. You can get the IP addresses without leaving Python. If you just need the non-loopback IP:
>>> socket.gethostbyname_ex(socket.gethostname())
('furby.home', [], ['192.168.1.5'])
>>> socket.gethostbyname_ex(socket.gethostname())[2][0]
'192.168.1.5'
And to get the loopback,
>>> socket.gethostbyname_ex('localhost')
('localhost', [], ['127.0.0.1'])
There's also a module called netifaces that'll do this in one fell swoop.
Upvotes: 3
Reputation: 3254
Thanks all . I could do this way.
ipa=[]
f=os.popen("ifconfig | grep -E 'inet.[0-9]' | awk '{ print $2}'")
for i in f.readlines():
ipa.append(i.rstrip('\n'))
return ipa
Upvotes: 1
Reputation: 10564
import subprocess
lines = subprocess.check_output(["ifconfig | grep -E 'inet.[0-9]' | awk '{ print $2
}'"]).split('\n')
Upvotes: 1
Reputation: 113915
Use sys.stdin
to read this output.
Then redirect the output as follows:
$ ifconfig | grep -E 'inet.[0-9]' | awk '{ print $2}' | myProg.py
Upvotes: 0