Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

python - Connecting to a server via another server using Paramiko

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

See Nested SSH using Python 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
')
stdin.flush()
stdin.write('subcommand
')
stdin.flush()

But this approach is error prone in general.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...