Connecting to a server via another server using Paramiko

烈酒焚心 提交于 2019-11-26 17:25:00

问题


I am trying to get into a server using Paramiko and then get into a router that's in the server and then run a command.

However, I am not getting a password input for the router and then it just closes the connection.

username, password, port = ...
router = ...
hostname = ...
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.WarningPolicy)
client.connect(hostname, port = port, username = username, password = password)

cmd = # ssh hostname@router

# password input comes out here but gets disconnected

stdin, stdout, stderr = client.exec_command(cmd) 

HERE # command to run in the router
stdout.read()

client.close()

Any help?


回答1:


First, you better use port forwarding (aka SSH tunnel) to connect to a server via another server.

There's a ready-made forward_tunnel function in Paramiko forward.py demo exactly for this purpose.

See also Port forwarding with Paramiko.


Anyway to answer your literal question:

  1. OpenSSH ssh needs terminal when prompting for a password, so you would need to set get_pty parameter of SSHClient.exec_command (that can get you lot of nasty side effects).

  2. Then you need to write the password to the command (ssh) input.

  3. And then you need to write the (sub)commands to the ssh input.
    See Execute (sub)commands in secondary shell/command on SSH server in Python Paramiko.

stdin, stdout, stderr = client.exec_command(cmd, get_pty=True) 
stdin.write('password\n')
stdin.flush()
stdin.write('subcommand\n')
stdin.flush()

But is approach is error prone in general.



来源:https://stackoverflow.com/questions/57210100/connecting-to-a-server-via-another-server-using-paramiko

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!