learnstuffnow49
learnstuffnow49

Reputation: 3

get ip address using os.system in python

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 ?

Upvotes: 0

Views: 1708

Answers (3)

doca
doca

Reputation: 1548

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

Upvotes: 0

user12421033
user12421033

Reputation: 1

Make it simple and use the below command :-

import os 

print(os.system("ifconfig"))

Upvotes: -1

Pierre D
Pierre D

Reputation: 26201

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))

Upvotes: 1

Related Questions