I want to write a program (in Python 3.x on Windows 7) that executes several commands on a remote shell via ssh. Looking at the exec_command() function, I realized that it is not suitable for my exec_command() use (since the channel closes after the command is executed), because the commands depend on environment variables (set by previous commands) and cannot be combined into one exec_command() since they must be executed at different times in the program.
Thus, I want to execute commands in one channel. The next option I learned was to implement an interactive shell using the invoke_shell() function:
ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(host, username=user, password=psw, port=22) channel = ssh.invoke_shell() out = channel.recv(9999) channel.send('cd mivne_final\n') channel.send('ls\n') while not channel.recv_ready(): time.sleep(3) out = channel.recv(9999) print(out.decode("ascii")) channel.send('cd ..\n') channel.send('cd or_fail\n') channel.send('ls\n') while not channel.recv_ready(): time.sleep(3) out = channel.recv(9999) print(out.decode("ascii")) channel.send('cd ..\n') channel.send('cd simulator\n') channel.send('ls\n') while not channel.recv_ready(): time.sleep(3) out = channel.recv(9999) print(out.decode("ascii")) ssh.close()
There are some problems with this code:
- The first
print does not always print the output of ls (sometimes it only prints on the second print ). - The first
cd and ls always present in the output (I get them through the recv command as part of the output), while all subsequent cd and ls sometimes printed, and sometimes not. - The second and third commands
cd and ls (when printed) always appear before the first output of ls .
I got confused with this βnon-determinismβ and would greatly appreciate your help.
misha source share