How to get output from netsh using python subprocess? - python

Can anyone please advise what am I doing wrong, that there is no output showed when executing netsh command on windows using python subprocess library?
Example:
p = subprocess.run('netsh dhcp show server', shell=True, stdout=subprocess.PIPE)
print(p.stdout.decode('utf-8'))
Output: empty string
When I execute some other command, etc. echo Hi, I get an output:
p = subprocess.run('echo Hi', shell=True, stdout=subprocess.PIPE)
print(p.stdout.decode('utf-8'))
My intention is to get list of our DHCP servers and parse the output.
Thanks!

Try to change the code page of the process to UTF-8 before executing sub-processes.
chcp 65001

Related

How to run more than one command with Python subprocess

I'm trying to run three commands with subprocess.Popen(), i don't know which is the problem.
The commands are running properly on the terminal but not on the code. Here is the code and the output.
str1 = os.path.join(install_path, "components", "esptool_py", "esptool", "esptool.py")
print(install_path) #/home/laura/esp/esp/idf
print(str1) #/home/laura/esp/esp-idf/components/esptool_py/esptool/esptool.py
str_result = "error has occurred, check if the credential in the \"input.config\" are correct"
cmd1 = f"cd {install_path}; . ./export.sh; python3 {str1} flash_id"
cmd = subprocess.Popen(cmd1, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
gui.write_on_output_text("1.0", "checking database for incorrect input on device code")
out, err = cmd.communicate()
out_str = str(out.decode("utf-8"))
THE OUTPUT:
/home/laura/esp/esp-idf
/home/laura/esp/esp-idf/components/esptool_py/esptool/esptool.py
/bin/sh: 22: ./export.sh: [[: not found
COMMAND IN TERMINAL THAT WORKS PROPERLY:
cd /home/laura/esp/esp-idf ; . ./export.sh ; python3 /home/laura/esp/esp-idf/components/esptool_py/esptool/esptool.py flash_id`
I don't know why in the terminal works, but in the code not. And i don't know if the error is that is NOT FINDING THE FILE or THE COMMAND.
Thank you :)
I already tried many ways to do it.
First i used the command gnome-terminal but it was not correct, because i don't want a new terminal I just want to send these 3 commands.
I know that in the terminal works because the response after send it is good, is what i expected, but in the code is not working, and I'm not sure if it's because Python cannot find the commands on /bin/sh, or if cannot find the file "export.sh".
I have this problem with the 3rd command too, it cannot find the "esptool.py"
I fix it with one of the ideas/resolutions on the comments.
subprocess.Popen(..., **executable='/bin/bash'**)
Just adding this :) The problem as they said, is that, i was trying to run with 'sh'

SSH to remote system and run python script and get output

I am playing with ssh and run the python scripts with help of these answers - Run local python script on remote server
For connecting the server using ssh, I am currently using the subprocess from python
#ssh command : ssh user#machine python < script.py - arg1 arg2
output = subprocess.Popen(f"ssh user#machine python3 < script.py", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
Now, I get the output of the script as tuples of bytes of string, it is hard to decode the output information. The output having other information like warnings.
I tried decoding the output, but that is not looks great,
Is there any other possible ways to get the output back from ssh, for example, the script.py print a python dictionary or returns a json data, which can get it back in the same format and save in the output variable?
Thanks
There are a couple of ways to do this with subprocess depending on how up to date your Python is.
In general any byte string in Python you can turn into 'proper' text by decoding it. In your example, the command is returning a tuple which is the output of (stdout, stderr) so we need to pick one of those tuple elements with output[0] or output[1]:
>>> output = subprocess.Popen(f"ssh git#github.com", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
>>> output[1].decode('utf-8')
"PTY allocation request failed on channel 0\r\nHi Chris! You've successfully authenticated, but GitHub does not provide shell access.\nConnection to github.com closed.\r\n"
You can tidy that up further by including the universal_newlines=True option.
Assuming you are Python 3.7 or later you can simplify your command so you capture a decoded output straight away:
>>> subprocess.run(['ssh', 'git#github.com'], capture_output=True, text=True).stderr
"PTY allocation request failed on channel 0\nHi Chris! You've successfully authenticated, but GitHub does not provide shell access.\nConnection to github.com closed.\n"
If you are struggling with the escaped newlines (\n) one approach would be to split them so you get an array of lines instead:
>>> output = subprocess.run(['ssh', 'git#github.com'], capture_output=True, text=True, universal_newlines=True).stderr.split("\n")
>>> output
['PTY allocation request failed on channel 0', "Hi Chris! You've successfully authenticated, but GitHub does not provide shell access.", 'Connection to github.com closed.', '']
>>> for line in output:
... print(line)
PTY allocation request failed on channel 0
Hi Chris! You've successfully authenticated, but GitHub does not provide shell access.
Connection to github.com closed.
print() will happily accept an array of terms to print, normally separated by a space. But you can override the separator:
print(*output, sep="\n")

Sending a command to terminal

Mpsyt is a terminal based library for Python. It provides to searching and playing music on youtube. This code which provides searching on youtube:
os.system("mpsyt search creep")
But then, i need to send a command to terminal which is "1". Because this "1" plays first music on searching list. How will i send "1" command to shell which is exist?
Try the following code..
import subprocess
p = subprocess.Popen(['mpsyt', 'search', 'creep'], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
print(p.communicate(b'1')[0].strip().decode('UTF-8'))
You can read the output of the subprocess by p.stdout.readline() command. Make sure there is something to be printed in console before writing that command. Otherwise your will program will stuck.

how to get output of grep command (Python)

I have an input file test.txt as:
host:dc2000
host:192.168.178.2
I want to get all of addresses of those machines by using:
grep "host:" /root/test.txt
And so on, I get command ouput via python:
import subprocess
file_input='/root/test.txt'
hosts=subprocess.Popen(['grep','"host:"',file_input], stdout= subprocess.PIPE)
print hosts.stdout.read()
But the result is empty string.
I don't know what problem I got. Can you suggest me how to solve?
Try that :
import subprocess
hosts = subprocess.check_output("grep 'host:' /root/test.txt", shell=True)
print hosts
Your code should work, are you sure that the user has the access right to read the file?
Also, are you certain there is a "host:" in the file? You might mean this instead:
hosts_process = subprocess.Popen(['grep','host:',file_input], stdout= subprocess.PIPE)
hosts_out, hosts_err = hosts_process.communicate()
Another solution, try Plumbum package(https://plumbum.readthedocs.io/):
from plumbum.cmd import grep
print(grep("host:", "/root/test.txt"))
print(grep("-n", "host:", "/root/test.txt")) #'-n' option

Capture output from a mysql select statement using python

Using Python2.4 I want to capture output from a mysql command. One caveat is that I need to pipe the SQL statement using an echo.
echo 'SELECT user FROM mysql.user;' | mysql
I see example using call, os.system, popen but what is best to use for my version of python and capturing the output in a tuple.
Thanks
The subprocess module is the most flexible tool for running commands and controlling the input and output. The following runs a command and captures the output as a list of lines:
import subprocess
p = subprocess.Popen(['/bin/bash', '-c', "echo 'select user from mysql.user;' | mysql" ],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
lines = [line for line in p.stdout]
On Windows, bash -c would be replaced with cmd /c.

Categories