Search code examples
pythonsshparamikotunnel

Keep alive mechanism for ssh over ssh in Paramiko


I'm using Paramiko interactive shell (invoke_shell() method) for opening session between my local host and remote host and sending commands to it.
Sometimes I need to open from my remote host an ssh connection to another remote host (this is like a bridge or SSH via SSH from local host to remote_host_2 via remote_host_1).

For better understanding this is a picture how it should behave:

| local host |  -(1)->    | remote host |  -(2)->   | destination host |   

1: is open using invoke_shell() paramiko method so it will create some paramiko.Channel obj.
2: is open using Linux command i.e. ssh remote_user@remote_ip

This is done this way because sometimes I have no direct connection to destination host and in case you are opening it via remote host then user decision should be made (entering another password, answering yes/no on some questions etc..)

Now my question is regarding keeping my connection alive.
I read on keep_alive mechanism that paramiko has but it doesn't do what I want because paramiko knows my connection ends in remote_host and not in destination host so in case destination host is dead I will not receive any notification regarding it and commands execution will fail.

The only solution that came to my mind is sending empty command on this channel (\n) and trying to read the output from the channel before executing the desirable command on it. but this means that I can affect my channel on one hand and my command execution time is now twice longer.

Now my question is, is there another way to perform this connection so this keep alive mechanism will work?

p.s. I read that there exists some ServerAliveInterval=30 flag that can help me to keep my ssh interactive connection alive but I don't understand how can I use it to validate it doesn't became dead.


Solution

  • The correct way is to implement the jump using port forwarding.
    See Connecting to a server via another server using Paramiko

    Then you will have a complete control over both connections and you will be able to use native Paramiko features to keep the connection alive and to check its status.