how to execute multiple lines using paramiko and read only their output

5.8k views Asked by At

How do I execute multiple commands using Paramiko and read the output back into my python script?

This question is theoretically answered here How do you execute multiple commands in a single session in Paramiko? (Python), but in my view that answer is incorrect.

The problem is that when you read the stdout, it reads the entire content of the terminal including the program that you "typed" into the terminal.

Just try it (this is basically a copy paste from the above thread):

import paramiko  
machine = "you machine ip"
username = "you username"
password = "password"
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(machine, username = username, password = password)
channel = client.invoke_shell()
stdin = channel.makefile('wb')
stdout = channel.makefile('rb')
stdin.write('''
cd tmp
ls
exit
''')
print stdout.read()
stdout.close()
stdin.close()
client.close()

So my question is, how do I execute multiple commands and read only the output of those commands, rather than the input I "typed" and the output?

Thanks in advance for your kind help and time.

3

There are 3 answers

0
poolie On

You're seeing the commands you typed because the shell echoes them back. You can turn this off by running

stty -echo

before your other commands.

Another approach is to not invoke an interactive shell, but just run the commands directly, unless there's some other reason you especially need an interactive shell. For instance you could say

client.exec_command('/bin/sh -c "cd /tmp && ls")

If you want a shell but without a pty, you can try

client.exec_command('/bin/sh')

and I think that will suppress the echo too.

1
SlickTester On
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
target_host = 'x.x.x.x'
target_port = 22  
target_port = 22
pwd = ':)'
un = 'root'
ssh.connect( hostname = target_host , username = un, password =pwd)
#Now exeute multiple commands seperated by semicolon
stdin, stdout, stderr = ssh.exec_command('cd mydir;ls')
print stdout.readlines()
0
firstname lastname On

This should work:

# Explicitly provide key, ip address and username
from paramiko import SSHClient, AutoAddPolicy

result = []

def ssh_conn():
    client = SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(AutoAddPolicy())

    client.connect('<host_IP_address>', username='<your_host_username>', key_filename='<private_key_location>')

    stdin, stdout, stderr = client.exec_command('ls -la')

    for each_line in stdout:
        result.append(each_line.strip('\n'))
    
    client.close()

ssh_conn()


for each_line in result:
    print(each_line.strip())