Search code examples
pythonsshtelnetparamikoportforwarding

Get command result from SSH/Telnet via another SSH jump server in Python


I am writing a Python code to SSH or Telnet remote hosts, execute some commands and get the result output. Here we have a jump server, so the code must be "connected" with this server and from it, Telnet or SSH the remote hosts.

All my approaches work fine within the jump server, for example I can get the output of commands inside it. The problem is when I try to remote connect to hosts from it.

import paramiko

client = paramiko.SSHClient()

client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('IP', 22, username="user", password="pass")
stdin, stdout, stderr = client.exec_command("command")
for line in stdout:
     print('... ' + line.strip('\n'))
client.close()

Using the library jumpssh get same results, and I am not will able to Telnet hosts. I tried the follow approach, but get the error

Administratively prohibited.

from jumpssh import SSHSession

gateway_session = SSHSession('jumpserver','user', password='pass').open()
remote_session = gateway_session.get_remote_session('IP',password='pass')
print(gateway_session.get_cmd_output('command'))

In the last company i worked we had a license from an SSH client that supports Python scripts, and worked fine in a more "textual" treatment.

There is any way of accomplish same task natively in Python?


Solution

  • SSHSession is trying to open direct-tcpip port forwarding channel over the gateway_session.

    "administratively prohibited" is OpenSSH sshd server message indicating that direct-tcpip port forwarding is disabled.

    To enable port forwarding, set AllowTcpForwarding and DisableForwarding directives in sshd_config appropriately.


    If you cannot enable the port forwarding on the server, you cannot use jumpssh library.

    If you have a shell access to the server, you can use ProxyCommand-like approach instead.
    See Paramiko: nest ssh session to another machine while preserving paramiko functionality (ProxyCommand).