Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Paramiko reuse a session or open a new one for each exec_command call?

I have a number of devices I need to test. To do so I need to execute commands over an SSH. I'm using Python and Paramiko. Here is the question. Every time I am running a command over SSH, does Paramiko open a new SSH session and creates a new process or keeps it open until I close it? It is important for be because I will have to run thousands of tests. Opening a new session each time will take a few extra seconds. If I can save this time over thousands of tests, I can save a lot of time.

If it doesn't keep the session open, how do I keep it open so I could execute commands without logging in every time, is it even possible? If it is not possible with Paramiko, can I do it with other modules?

I found this but they all seem to be either wrappers around Paramiko or they are outdated.

Her is an example of command I'm trying to execute:

hostname = '192.168.3.4'    
port = 22
username = 'username'
password = 'mypassword'
s = paramiko.SSHClient()
s.load_system_host_keys()
s.connect(hostname, port, username, password)
command = 'ls -lah'
(stdin, stdout, stderr) = s.exec_command(command)
(stdin, stdout, stderr) = s.exec_command(command)
(stdin, stdout, stderr) = s.exec_command(command)
(stdin, stdout, stderr) = s.exec_command(command)
like image 705
flashburn Avatar asked Nov 14 '25 19:11

flashburn


1 Answers

It depends on what part of the code do you repeat for each command.


If you repeat only the SSHClient.exec_command call, you are still using the same connection.

For internals of exec_command, see my answer to:
What is the difference between exec_command and send with invoke_shell() on Paramiko?


If you repeat your whole code, including the SSHClient.connect, you are obviously logging in every time again.

like image 116
Martin Prikryl Avatar answered Nov 17 '25 09:11

Martin Prikryl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!