Home > Net >  Append results from a shell command to a list in Python
Append results from a shell command to a list in Python

Time:02-11

I wrote a shell command inside Python to collect the IPv4 address in a server.

# cat ipv4.py
#!/usr/bin/env python3
import os
ipv4_regex = r'[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
os_cmd = f"ip a s eth0 | egrep -o 'inet {ipv4_regex}' | cut -d' ' -f2"
os.system(os_cmd)

Output:

# ./ipv4.py
192.168.0.2
192.168.0.3
192.168.0.4

How do I append each IPv4 address from the above output to a list in Python?.

CodePudding user response:

This should do the trick:

import subprocess
x = subprocess.check_output(['os_cmd'])

CodePudding user response:

First of all, the return of the os.system() method you are invocating is not directly what you are expecting. Instead, try using os.popen(), it is the same, essentialy, as the subprocess check_output() method:

import os
ipv4_regex = r'[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'
os_cmd = f"ip a s eth0 | egrep -o 'inet {ipv4_regex}' | cut -d' ' -f2"
x = os.popen(os_cmd).read()

Afterwards you can do some treatment in order get the return in the desired structure, creating a list from each line of x as example:

ips_list = x.split('\n')

CodePudding user response:

  1. You'll need the subprocess module to capture output from a process.
  2. You'll probably have a better time finding your matches in Python rather than build a shell pipeline.
import re
import subprocess
import shlex

match_re = re.compile(
    r"inet ([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})"
)


def get_ips(interface_name):
    ips = match_re.findall(
        subprocess.check_output(
            f"ip a s {shlex.quote(interface_name)}",
            shell=True,
            encoding="utf-8",
        )
    )
    return ips


print(get_ips("eno1"))

This directly prints out (e.g.)

['192.168.1.20']

since findall() gets you the first capture group from the regexp.

  • Related