0

Im new to python and Im trying to get the IP Address of my network card using the following:

import sys
import os



ip_address = os.system('/sbin/ifconfig ens33 | grep "inet" |awk '/inet / { print $2 }' | cut -d":" -f2')

However it returns the following error:

ip_address = os.system('/sbin/ifconfig ens33 | grep "inet" |awk '/inet / { print $2 }' | cut -d":" -f2')
                                                                                 ^

SyntaxError: invalid syntax

If I just have in up to here it get some of the output:

ip_address = os.system('/sbin/ifconfig ens33 | grep "inet" ')

inet 192.168.130.130 netmask 255.255.255.0 broadcast 192.168.130.255 inet6 fe80::97b9:2816:c3a3:e02e prefixlen 64 scopeid 0x20

Is there a way to do this using os and sys ?

5
  • 3
    Your inner single quotation marks need to be escaped. Commented Nov 25, 2022 at 16:30
  • 3
    Even if you fix the syntax errors this isn't going to work...os.system() does not return the output of the command. You're going to want to look at the subprocess module. Commented Nov 25, 2022 at 16:37
  • 2
    If you don't want to concern yourself with proper escaping of inner quotation marks, enclose the whole command line between a pair of three-quotes """. However, why do you need to feed the results of ifconfig through grep and awk? You can just process it in Python... Commented Nov 25, 2022 at 16:37
  • Thanks Klaus, Ive altered it now to be: ip_address = os.system('/sbin/ifconfig ens33 | grep "inet" |awk \'/inet / { print $2 }\' | cut -d":" -f2') That prints out : 192.168.130.130 0 How do I get it to not print the "0" Commented Nov 25, 2022 at 16:38
  • "Is there a way to do this using os and sys ?" you shouldn't be using os.sytem, use the subprocess module Commented Nov 25, 2022 at 19:27

3 Answers 3

1

Here is a way:

import subprocess

cmd = """/sbin/ifconfig eth0 | grep "inet" | awk '/inet / { print $2 }' | cut -d: -f2"""
r = subprocess.run(cmd, shell=True, capture_output=True, universal_newlines=True)
private_ip = r.stdout.strip()

>>> obfuscate_ip(private_ip)  # see footnote
'55.3.93.202'

(For your case: use ens33 instead of eth0).

That said, you are better off using socket:

import socket

def get_private_ip():
    with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as st:
        st.settimeout(0.0)
        try:
            st.connect(('8.8.8.8', 80))
            ip = st.getsockname()[0]
        except socket.error:
            ip = '127.0.0.1'
    return ip

private_ip2 = get_private_ip()

>>> obfuscate_ip(private_ip2)
'55.3.93.202'

And:

assert private_ip2 == private_ip

Footnote: I don't like to reveal my actual IP address (even if just the private one). Thus:

import numpy as np
import contextlib

@contextlib.contextmanager
def seed_context(seed):
    state = np.random.get_state()
    np.random.seed(seed)
    try:
        yield
    finally:
        np.random.set_state(state)

def obfuscate_ip(ip):
    with seed_context(id(obfuscate_ip) >> 16):
        mul = np.random.randint(1, 255, 4)
        off = np.random.randint(1, 255, 4)
        parts = (np.array([int(x) for x in ip.split('.')]) * mul + off) % 256
        return '.'.join(map(str, parts))
Sign up to request clarification or add additional context in comments.

1 Comment

you should probably just use subprocess.run()
0

os.system runs the command in the shell but does not return the output so that you can capture it into a variable. You need something like subprocess.Popen to get the command output.

import subprocess

stdout, _ = subprocess.Popen("ifconfig", shell=True, stdout=subprocess.PIPE).communicate()
stdout = stdout.decode() # above returned value is a binary string

Then you can filter out the stdout and get what you need.

If you have only one IP, it might be easier to use hostname -I command instead

Comments

-1

Make it simple and use the below command :-

import os 

print(os.system("ifconfig"))

1 Comment

This does not answer the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.