1
votes

I've seen several questions and answers related to this topic but I've been unable to grasp the howto.

  1. What I'm able to do : connect to a remote computer using a Python script using Paramiko and return information, for instance, to ping a switch :

    ssh = pk.SSHClient()

    ssh.set_missing_host_key_policy(pk.AutoAddPolicy())

    ssh.connect('{}'.format(IP), port=xxx, username='xxx',password='xxx')

    stdin, stdout, stderr = \

    ssh.exec_command('ping -n 1 xxx.xxx.x.x\n')

    print('Ping switch: \n', stdout.readlines())

  2. What I would like to do but don't know how to : connect once to the computer and then using SSH (paramiko.SSHClient()) again connect to another device (in this case a NAS) and 'exec_command', something like :

    ssh = pk.SSHClient()

    ssh.set_missing_host_key_policy(pk.AutoAddPolicy())

    ssh.connect('{}'.format(IP), port=xxx, username='xxx',password='xxx') # connect to computer

    ssh.connect('{}'.format(IP), port=xxx, username='xxx',password='xxx') #connect to NAS from computer

    stdin, stdout, stderr = \

    ssh.exec_command('shutdown\n, y\n') # send command to NAS

    print('Ping switch: \n', stdout.readlines())

enter image description here

Is this possible, does anyone know a way?

Thank you in advance.

2

2 Answers

0
votes

You have to open a tunnel, check paramiko demo or use sshtunnel package. For the latter:

import paramiko as pk
import sshtunnel

with sshtunnel.open_tunnel(
    remote_computer_ip,
    ssh_username=remote_username,
    ssh_password=remote_password,
    remote_bind_address=(NAS_IP, 22),
    debug_level='DEBUG',
) as tunnel:
    ssh = pk.SSHClient()
    ssh.set_missing_host_key_policy(pk.AutoAddPolicy())
    ssh.connect(NAS_IP,
                port=tunnel.local_bind_port,  # redirected to port NAS_IP:22
                username=NAS_USER,
                password=NAS_PASS)
    (stdin, stdout, stderr) = ssh.exec_command(...)   # your stuff
-1
votes

You could ask the question in a more simpler way. If I am not wrong are you trying to connect to one machine using paramiko and from that machine you want to connect to NAS machine?

Or is that you connect to 1 machine say A and then you want the ssh handle of that machine and connect to NAS machine and generate another ssh handle?

If latter is the case, I would suggest you to use a class and create an object for every ssh connect. You can have a look at this:

ssh.py