3

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
  • 167,268
  • 50
  • 405
  • 846
flashburn
  • 3,734
  • 3
  • 45
  • 90

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
  • 167,268
  • 50
  • 405
  • 846
  • When I run `exec_command`, is a new process created on the client (i.e. machine which runs `python` and uses `paramiko`) or `paramiko` simply sends the command over a channel that it has connected to? Again goes back to the optimization. If I don't have to create a new process every time a command is executes I can save a lot of time. – flashburn Jun 21 '19 at 20:02
  • Paramiko does not create any process. Did you think that Paramiko runs over `ssh` process? It does not, Paramiko is a native Python implementation of SSH. – Martin Prikryl Jun 21 '19 at 20:04
  • So to clarify for me. Once I connect, I create a tunnel (so to speak) over which I can execute commands. I don't login every time I execute a command. – flashburn Jun 21 '19 at 20:17
  • 1
    To be exact: you do not login every time you call `exec_command`. – Martin Prikryl Jun 21 '19 at 20:18
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/195372/discussion-between-flashburn-and-martin-prikryl). – flashburn Jun 21 '19 at 20:25
  • I've added a link with details to my answer. – Martin Prikryl Jun 21 '19 at 20:26