How do you execute multiple commands in a single session in Paramiko? (Python)
Non-Interactive use cases
This is a non-interactive example... it sends cd tmp
, ls
and then exit
.
import sys
sys.stderr = open('/dev/null') # Silence silly warnings from paramiko
import paramiko as pm
sys.stderr = sys.__stderr__
import os
class AllowAllKeys(pm.MissingHostKeyPolicy):
def missing_host_key(self, client, hostname, key):
return
HOST = '127.0.0.1'
USER = ''
PASSWORD = ''
client = pm.SSHClient()
client.load_system_host_keys()
client.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
client.set_missing_host_key_policy(AllowAllKeys())
client.connect(HOST, username=USER, 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()
Interactive use cases
If you have an interactive ssh use case, paramiko can handle it but this answer won't help... I personally would use something based on exscript
(which uses paramiko) or pexpect
for interactive ssh sessions.
Execute two commands in a row using one SSH object via paramiko
It's not
ssh.exec_command('command1' ; 'command2')
Should be
ssh.exec_command('command1 ; command2')
Execute multiple dependent commands individually with Paramiko and find out when each command finishes
It seems that you want to implement an interactive shell, yet you need to control individual commands execution. That's not really possible with just SSH interface. "shell" channel in SSH is black box with an input and output. So there's nothing in Paramiko that will help you implementing this.
If you need to find out when a specific command finishes or where an output of a specific command ends, you need to use features of a shell.
You can solve that by inserting a unique separator (string) in between and search for it in the channel output stream. With a common *nix shells something like this works:
channel = ssh.invoke_shell()
channel.send('cd /mytargetRep\n')
channel.send('echo unique-string-separating-output-of-the-commands\n')
channel.send('./executeWhatIWant\n')
Though I do not really think that you need that very often. Most commands that are needed to make a specific commands working, like cd
or set
, do not really output anything.
So in most cases you can use SSHClient.exec_command
and your code will be a way simpler and more reliable:
Execute multiple commands in Paramiko so that commands are affected by their predecessors
Even if you need to use something seemingly complex like su
/sudo
, it is still better to stick with SSHClient.exec_command
:
Executing command using "su -l" in SSH using Python
For a similar question, see:
Combining interactive shell and recv_exit_status method using Paramiko
Python paramiko module using multiple commands
With just paramiko
after the exec_command
executes the channel is closed and the ssh
returns an auth prompt.
Seems its not possible with just paramiko
, try fabric
or another tool.
** fabric
did not work out too.
How do you execute multiple commands in a single session in Paramiko? (Python)
Non-Interactive use cases
This is a non-interactive example... it sends cd tmp
, ls
and then exit
.
import sys
sys.stderr = open('/dev/null') # Silence silly warnings from paramiko
import paramiko as pm
sys.stderr = sys.__stderr__
import os
class AllowAllKeys(pm.MissingHostKeyPolicy):
def missing_host_key(self, client, hostname, key):
return
HOST = '127.0.0.1'
USER = ''
PASSWORD = ''
client = pm.SSHClient()
client.load_system_host_keys()
client.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
client.set_missing_host_key_policy(AllowAllKeys())
client.connect(HOST, username=USER, 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()
Interactive use cases
If you have an interactive ssh use case, paramiko can handle it but this answer won't help... I personally would use something based on exscript
(which uses paramiko) or pexpect
for interactive ssh sessions.
Related Topics
How to Hide Tkinter Python Gui
How to Drop Rows of Pandas Dataframe Whose Value in a Certain Column Is Nan
How to Open Excel File Fast in Python
Conda: Remove All Installed Packages from Base/Root Environment
Subtracting Values Across Grouped Data Frames in Pandas
In Python, How to Check If a String Only Contains Certain Characters
Sort Array and Return Original Indexes of Sorted Array
Masking Horizontal and Vertical Lines With Open Cv
Best Way to Identify and Extract Dates from Text Python
How to Extract Table Names and Column Names from SQL Query
_Corrupt_Record Error When Reading a Json File into Spark
How to Do an Upsert With Sqlalchemy
How to Print Specific Key Value from a Dictionary
Sqlalchemy: How to Filter Date Field
Finding Length of the Longest List in an Irregular List of Lists
Python Number With 1000 Separator
How to Remove Commas and Dots of Individual Word in Two Dimensional List