0
votes

I'm using Paramiko in Python 2.7 to connect to a linux server and the program works fine. The problem is that when I run it I get this output from the IDE:

Start
This is a test program
before the cd..
after the cd ..
after the pwd
after the ls
/home/11506499

End

My code looks like this:

import paramiko
ssh = paramiko.SSHClient()

print('Start')
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('XXX.XX.XXX.XX', port = 22, username = 'tester', password = 'test')

print("This is a test program")

stdin, stdout, stderr = ssh.exec_command('pwd')

print('before the cd..')
stdin.write('cd ..')
stdin.write('\n')
stdin.flush()

print('after the cd ..')
stdin.write('pwd')
stdin.write('\n')
stdin.flush()

print('after the pwd')
stdin.write('ls')
stdin.write('\n')
stdin.flush()

print('after the ls')
output = stdout.readlines()
print '\n'.join(output)

ssh.close()
print('End')

As you can see on the prints the program runs through all the commands but stdout only shows the output from the first ssh.exec_command (the 'pwd') and not from all the stdin.write. What I want to know is if there's a way or command to get the output from the other commands I sent through the terminal? I'm thinking of the commands such as the second 'pwd' or the 'ls' command?

Is there a way to show the output for the response for each action I take in the terminal as was I using cmd.exe or a terminal in Linux?

I've tried looking on the net but haven't been able to see anything since the examples only show the output from the first command only. So I hope someone can help me with this problem.


Edit: I went away from making a client connection and instead went with a shell which will keep the connection until I log out. I used recv to store the output from the terminal and print to printing it out. This worked wonders.

I did though import time so the script could take a little break where it could collect the rest of the output before printing it out. This way I was able to print out everything appearing in the terminal without it being lacking.

1

1 Answers

2
votes

You are only executing one command in your script. From my understanding, stdin in your case would be used to pass arguments into a running command. Meaning you would have to individually run ssh.exec_command(<cmd>) for pwd, cd, and ls. After your initial execution, the session closes and you are not able to issue more commands.

This is just like issuing the command

ssh user@hostname "pwd"

The session has completed and the connection is closed. It's not quite like telnet where you simply type a command and add '\n' to execute it, nor like a bash prompt because you are not starting a tty.

Regards,
Lisenby