4

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)
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
flashburn
  • 4,180
  • 7
  • 54
  • 109

1 Answers1

2

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.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992