Dawn17
Dawn17

Reputation: 8297

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?

Upvotes: 2

Views: 4483

Answers (1)

Martin Prikryl
Martin Prikryl

Reputation: 202534

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\n')
stdin.flush()
stdin.write('subcommand\n')
stdin.flush()

But this approach is error prone in general.

Upvotes: 1

Related Questions