-4

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?

  • 1
    Relevant [Retrieving the output of subprocess.call()](https://stackoverflow.com/a/1996540/7414759) and [Regular expression matching a multiline block of text](https://stackoverflow.com/a/587620/7414759) – stovfl Jul 14 '20 at 18:14

2 Answers2

0
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

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Kistler
  • 1
  • 1
  • Please add some explanation – mechnicov Jul 28 '20 at 10:08
  • Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Dima Kozhevin Jul 28 '20 at 12:26
  • Excuse me, I am new to this forum. I hope that my subsequently added explanations are satisfactory. – Kistler Jul 28 '20 at 13:40
  • Please make sure to keep text outside of code blocks. I have edited your answer to fix that. – Mark Rotteveel Jul 28 '20 at 14:33
0

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.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Kistler
  • 1
  • 1