Search code examples
pythonpython-3.xbashpython-os

Problem executing regex with a shell command inside Python program


I am trying to write a Python script to automate some tasks while the event of high inbound connections to the server.

So a portion of it is to collect all the IPv4 addresses on the server.

The command helps to list out that.

# ip a s eth0 | egrep -o 'inet [0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | cut -d' ' -f2
198.168.1.2
198.168.1.3
198.168.1.4

The problem I am facing when executing the shell regex part inside the python script.

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

But the output is error:

# ./dos_fix.py
  File "./dos_fix.py", line 4
    os_cmd = 'ip a s eth0 | egrep -o 'inet ipv4_regex' | cut -d' ' -f2'
                                     ^

To see if it was due to any whitespace interrupting between the egrep and pipe, I tried to escape those quotes with backslashes, but no luck.

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

What am I missing here?.


Solution

  • Use double quotes and don't escape.

    In the regular expression, use a raw string: r'contents'.

    os.system has some limitations. subprocess is much better.

    #!/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)