I have an application where I configure Cisco Routers in a LAB environment through a Console Server.
The routers can be reached via SSH. Sometimes after a program exit/crash the ssh connection is not terminated.
After a restart I cannot login to that specific router while the port on the console server is blocked.
To unblock it I need to terminate that ssh session.
If I have more sessions in use I do not know which of them I need to terminate, so I would like to get the source port when the connection was built by paramiko/netmiko.
Did somebody did this before, or maybe somebody has an idea.
To get the Paramiko SSH connection's underlying socket, use ssh.get_transport().sock
.
Then, see How do I print the local and remote address and port of a connected socket?
So usually, this will work:
port = ssh.get_transport().sock.getsockname()[1]
But that makes couple of assumptions. As you do not need to use the port number programatically, safer is to just print the complete result of getsockname()
, rather than assuming that the result is a tuple with a port at index 1.