I would like to find only the IP address from the command output of ifconfig
:
import os
ip = os.system("ifconfig eth0")
How do I then find 192.168.1.10
from the output and print that to standard output?
I would like to find only the IP address from the command output of ifconfig
:
import os
ip = os.system("ifconfig eth0")
How do I then find 192.168.1.10
from the output and print that to standard output?
ip=os.system("ifconfig eth0|grep -w 'inet'|awk '{print $2}'")
This solution is with pure shell commands. Grep searches for the word inet and prints the line, awk then filters for the second word and this is the IP
or
import subprocess
import re
ip=subprocess.Popen(['ifconfig', 'eth0'], stdout=subprocess.PIPE).communicate()[0]
oip=re.search(r"[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}", str(ip))
print(oip.group())
Here regular expressions are applied to the ifconfig command. The first occurrence of a string is searched for, which has 4 numbers, each number maximum 3 digits long, separated by a dot.