0

So I have a project I'm working on, and one thing I need to do is to run in the background the "netstat -nb" command at the PowerShell as admin and recive the results to the python program. I've been searching the web for a solution but never found one efficient out there. I'd be glad for some help.

"netstat -nb"

2 Answers 2

1

If you want to execute the netstat command you can do so from Python directly.But you need to be running Python script as a Admin:

import subprocess 
subprocess.call("netstat -nb")

If you need to access the powershell netstat values inside the Python script then you can set variable in powershell and pass it to Python script. Following is the powershell command:

$con=netstat -nb
& python.exe "FullPath of Python script file"-p $con

Python script:

import sys
print(sys.argv[5])

for conn in sys.argv:
   print(conn)

Here we are looping the parameters passed (netstat output) and displaying.So you are passing powershell command result to Python script and displaying it there. Following columns would be displayed:

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Im running the .py program through cmd
0

You can use subprocess library. About subprocess module you can check this documentation for more detail and features. It helps you to solve your problem. You can use subprocess.Popen or subprocess.call or to get output from another script you can use subprocess.check_output.

You can use it like this piece of code:

import subprocess
import sys
output = subprocess.Popen(['python','sample.py','Hello'],stdout=subprocess.PIPE).communicate()
print(output)

Inside of the sample.py script is:

import sys
my_message = "This is desired output. " + sys.argv[1]
print(my_message)

In your case you can use Popen as:

subprocess.Popen(['netstat','-nb'],stdout=subprocess.PIPE).communicate()

Comments

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.