1

The other questions aren't quite the same.

What I'm looking at achieving is a Python function which returns a list of all the IP addresses on a system, emulating the behaviour of:

ifconfig | grep 'inet addr:' | grep -v 127.0.0.1 | cut -d: -f2 | awk '{ print $1}'
Kulbir Saini
  • 3,926
  • 1
  • 26
  • 34
Ivy
  • 3,393
  • 11
  • 33
  • 46

1 Answers1

5

You can use the subprocess python module to achieve this.

import subprocess
cmd = "ifconfig | grep 'inet addr:' | grep -v 127.0.0.1 | cut -d: -f2 | awk '{ print $1}'"
co = subprocess.Popen([cmd], shell = True, stdout = subprocess.PIPE)
ips = co.stdout.read().strip().split("\n")

That should give you a list of IP addresses.

PS : It'll be better to use the following command instead

ifconfig | grep inet | grep -v inet6 | grep -v 127.0.0.1 | awk '{print $2}' | cut -d\: -f2 | cut -d\  -f1

This will exclude IPV6 addresses if any.

Pure Python Way

If you are looking to do this entirely in Python, then checkout netifaces python module.

Kulbir Saini
  • 3,926
  • 1
  • 26
  • 34
  • 1
    This works well. I can't use netifaces because it's not included in Python by default and I need to run this on multiple remote hosts – Ivy Jul 16 '12 at 09:35
  • You could install netifaces. After all, someone installed Python. Also, the chances that netifaces will work on random machines is a bit higher than the chances that ifconfig, grep, awk, and cut will all behave exactly the same (without option tweaking, etc) on random machines. You might at least consider doing the string parsing in *Python* so that you *only* have to run ifconfig and not rely on those other tools and shell pipelines. – Jean-Paul Calderone Jul 16 '12 at 11:40
  • netifaces is not "put python" in that it requires a built C module – jeckhart Jan 23 '13 at 23:13
  • The extremely inefficient `grep | grep | awk` would be easy to replace with pure Python, and also avoid the `shell=True` which is a bit of a security issue. See also http://stackoverflow.com/a/32713301/874188 – tripleee Sep 22 '15 at 09:35