Execute multiple commands in Paramiko so that commands are affected by their predecessors

When you run exec_command multiple times, each command is executed in its own “shell”. So the previous commands have no effect on an environment of the following commands.

If you need the previous commands to affect the following commands, just use an appropriate syntax of your server shell. Most *nix shells use a semicolon or an double-ampersand (with different semantics) to specify a list of commands. In your case, the ampersand is more appropriate, as it executes following commands, only if previous commands succeed:

command = "ORACLE_SID=PROD && cd /01/application/dataload && pwd"
stdin,stdout,stderr = ssh.exec_command(command)

In many cases, you do not even need to use multiple commands.

For example, instead of this sequence, that you might do when using shell interactively:

cd /path
ls

You can do:

ls /path

See also:
How to get each dependent command execution output using Paramiko exec_command


Obligatory warning: Do not use AutoAddPolicy on its own – You are losing a protection against MITM attacks by doing so. For a correct solution, see Paramiko “Unknown Server”.

Leave a Comment