This is a simple code that logs into a linux box, and execute a grep to a resource on the box. I just need to be able to view the output of the command I execute, but nothing is returned. Code doesn't report any error but the desired output is not written.
Below is the code:
import socket
import re
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('linux_box', port=22, username='abc', password='xyz')
stdin, stdout, stderr = ssh.exec_command('grep xyz *.set')
output2 = stdout.readlines()
type(output2)
This is the output I get:
C:\Python34\python.exe C:/Python34/Paramiko.py
Process finished with exit code 0
You never actually print anything to standard output.
Changing last line to print(output2) should print value correctly.
Your code was likely based on interactive Python shell experiments, where return value of last executed command is printed to standard output implicitly. In non-interactive mode such behavior does not occur. That's why you need to use print function explicitly.
Related
I'm reading the Wi-Fi connection of my Raspberry Pi, using the iwgetid command.
The output is:
wlan0 ESSID:"iPhone"
I wrote the following lines in a Python script:
import os
print(os.system("iwgetid"))
print(type(os.system("iwgetid")))
The output I got was:
0
<type 'int'>
Why is print(os.system("iwgetid") giving me 0 when it's a string?
As quoted from here:
os.system() just runs the process, it doesn't capture the output:
If command generates any output, it will be sent to the interpreter
standard output stream. The return value is the exit code of the
process:
On Unix, the return value is the exit status of the process encoded in
the format specified for wait().
To get the output from the Terminal command, use the subprocess module and the command subprocess.check_output instead of os.system.
I am trying to build a system where a list of the available wifi networks would be stored for some specific purpose. Now the problem is that executing a system command with os.system() in a variable 'res' only stores the return value of the command which is useless to me at this point.
I know of no approach that provide me the desired result.
import os
res = os.system('nmcli dev wifi')
The variable res must store all the desired result into it rather than the return value. Even if it stores result, it will do the work.
You can do this using the Popen method from the subprocess module
from subprocess import Popen, PIPE
#First argument is the program name.
arguments = ['ls', '-l', '-a']
#Run the program ls as subprocess.
process = Popen(arguments, stdout=PIPE, stderr=PIPE)
#Get the output or any errors. Be aware, they are going to be
#in bytes!!!
stdout, stderr = process.communicate()
#Print the output of the ls command.
print(bytes.decode(stdout))
I want to pipe data via stdin to a Python script for onwards processing. The command is:
tail -f /home/pi/ALL.TXT | python3 ./logcheck.py
And the Python code is:
import sys
while 1:
if (sys.stdin.isatty()):
for line in sys.stdin:
print(line)
I want the code to continuously watch stdin and then process each row when received. The tail command is working when run on its own but the python script never outputs anything.
Checking isatty() it appears to always return False?
Help!
A TTY is when you use your regular terminal - as in opening up a python in your shell, and typing
BASH>python
>>>from sys import stdin
>>>stdin.isatty() #True
In your case the standard input is coming from something which is not a tty. Just add a not in the if statement.
I am trying to use the subprocess module of Python 3 to call a command (i.e. netstat -ano > output.txt), but when I run the script, the output file gets created, but nothing gets written into it, in other words, its just blank.
I've tried looking into the subprocess module API about how the subprocess.call() method works, and searching Google for a solution. I tried using the subprocess.check_output() method, but it printed it out as an unformatted string, rather than the column-like format that entering netstat -ano into Windows command prompt usually gives.
This is my current code:
import subprocess as sp
t = open('output.txt', 'w')
command = 'netstat -ano > output.txt'
cmd = command.split(' ')
sp.call(cmd) # sp.call(['netstat', '-ano', '>', 'output.txt'])
t.close()
I thought it was maybe because I didn't use the write() method. But when I changed my code to be
t.write(sp.call(cmd))
I would get the error that the write() method expects a string input, but received an int.
I expected the output to give me what I would normally see if I were to open command prompt (in Windows 10) and type netstat -ano > output.txt, which would normally generate a file called "output.txt" and have the output of my netstat command.
However when I run that command in my current script, it creates the 'output.txt' file, but there's nothing written in it.
If you just cast your cmd to a str like t.write(str(cmd))it will write to output.txt
import subprocess as sp
t = open('output.txt', 'w')
command = 'netstat -ano > output.txt'
cmd = command.split(' ')
t.write(str(cmd))
sp.call(cmd) # sp.call(['netstat', '-ano', '>', 'output.txt'])
t.close()
I have this fun in my python script:
def start_pushdata_server(Logger):
Logger.write_event("Starting pushdata Server..", "INFO")
retcode, stdout, stderr = run_shell(create_shell_command("pushdata-server
start"))
we want to redirect the standard error from pushdata-server binary to /dev/null.
so we edit it like this:
def start_pushdata_server(Logger):
Logger.write_event("Starting pushdata Server..", "INFO")
retcode, stdout, stderr = run_shell(create_shell_command("pushdata-server
start 2>/dev/null"))
But adding the 2>/dev/null in the python code isn't valid.
So how we can in the python code to send all errors from "pushdata-server
start" to null?
This code added to a Python script running in Unix or Linux will redirect all stderr output to /dev/null
import os # if you have not already done this
fd = os.open('/dev/null',os.O_WRONLY)
os.dup2(fd,2)
If you want to do this for only part of your code:
import os # if you have not already done this
fd = os.open('/dev/null',os.O_WRONLY)
savefd = os.dup(2)
os.dup2(fd,2)
The part of your code to have stderr redirected goes here. Then to restore stderr back to where it was:
os.dup2(savefd,2)
If you want to do this for stdout, use 1 instead of 2 in the os.dup and os.dup2 calls (dup2 stays as dup2) and flush stdout before doing any group of os. calls. Use different names instead of fd and/or savefd if these are conflicts with your code.
Avoiding the complexities of the run_shell(create_shell_command(...)) part which isn't well-defined anyway, try
import subprocess
subprocess.run(['pushdata-server', 'start'], stderr=subprocess.DEVNULL)
This doesn't involve a shell at all; your command doesn't seem to require one.