atrax
atrax

Reputation: 3

Using python os.system to extract port from netstat and use it in variable

I am looking for a solution to extract port from netstat and use it as variable. Issue is that when I print it, value is 0 although when I use same command in bash it returns correct port.

device_port = os.system("netstat -atnp 2>/dev/null | awk '/adb/ {print $4}' | cut -d ':' -f 2")

returns value 5037

print(device_port)

returns value 0

Im not sure why is this happening.

Thanks

Upvotes: 0

Views: 714

Answers (1)

Finomnis
Finomnis

Reputation: 22396

Your first command doesn't return 5037, it prints 5037. That's a difference.

Look at the documentation of os.system: https://docs.python.org/3/library/os.html#os.system

It states that it will forward the stdout of the command to the console, and return the exit code of the command.

That's exactly what happens, your code prints 5037 to the console and returns 0 to indicate that the command succeeded.


Fix:

Use subprocess instead of os.system. It's even recommended in the official documentation of os.system. That will allow you to capture the output and write it to a variable:

import subprocess

command = subprocess.run("netstat -atnp 2>/dev/null | awk '/adb/ {print $4}' | cut -d ':' -f 2",
    check=True,  # Raise an error if the command failed
    capture_output=True,  # Capture the output (can be accessed via the .stdout member)
    text=True,  # Capture output as text, not as bytes
    shell=True)  # Run in shell. Required, because you use pipes.
    
device_port = int(command.stdout)  # Get the output and convert it to an int
print(device_port)  # Print the parsed port number

Here's a working example: https://ideone.com/guXXLl

I replaced your bash command with id -u, as your bash script didn't print anything on ideome, and therefore the int() conversion failed.

Upvotes: 1

Related Questions