Home > database >  Make Python Subprocess Run in PowerShell
Make Python Subprocess Run in PowerShell

Time:07-23

I'm trying to cmd vs ps

I do not want to use powershell -Command, nor saving the commands into a .ps1 file.

Could I make subprocess.run to run specifically in PowerShell?

CodePudding user response:

The documentation says subprocess() uses COMSPEC to determine which shell to run if you set shell=True.

I don't have, want, or use Windows, but imagine you'd need something like:

import os
import subprocess

# Change COMSPEC to point to Powershell
os.putenv('COMSPEC',r'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe')

subprocess.run(..., shell=True)

I'm assuming you can check that path.


I guess it would probably be good practice to save and restore the previous COMSPEC in case the change to Powershell upsets something else. So:

# Save original COMSPEC
savedCOMSPEC = os.getenv('COMSPEC')

... CODE FROM ABOVE ...

# Restore previous COMSPEC
os.putenv('COMSPEC', savedCOMSPEC)

CodePudding user response:

Option 1:

You could go about this by pip-installing nmap in powershell by running powershell as administrator and running:

pip install nmap
pip install python-nmap

Then, head back to your python script, call powershell using subprocess.call followed by your path to powershell.exe, then the desired command to execute:

import subprocess
from subprocess import call

subprocess.call(f'C:\Windows\System32\powershell.exe nmap -T4 -p 37000-44000', shell=True)

OR

Option 2:

You could just import nmap as a package into your python script, still making sure that you pip-installed nmap AND python-nmap.

import nmap
scan = nmap.PortScanner()

scan.scan({ip}, '37000-44000')

I found a detailed article explaining how to do the latter method. (Importing nmap directly into your script as a package, that is.)

Best of luck and happy coding! ;)

  • Related