0

Im looking to write a python script which need to perform the following:

  1. SSH into host A
  2. From host A, SSH into host B (host B can be connected only from host A)
  3. From host B, Execute set of commands and show the output on screen

Could someone please advise on how to achieve this?

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
devops1
  • 1
  • 3
  • What have you tried so far? – Klaus D. Feb 24 '22 at 13:31
  • you need first accomplish the same task using commands(ssh port-forward is one solution), understand the mechanism, then try python. – Lei Yang Feb 24 '22 at 13:34
  • 1
    The answers here might be of help - https://stackoverflow.com/questions/8169739/how-to-create-a-ssh-tunnel-using-python-and-paramiko – jsbueno Feb 24 '22 at 13:34
  • This is basically what the `-J` option is for. From your perspective, you just connect to B from your local host, telling `ssh` to "use" host A to do so. – chepner Feb 24 '22 at 13:50

1 Answers1

-1

i did something similar with paramiko:

from paramiko.client import SSHClient, AutoAddPolicy

class SSHCmd(object):

    def __init__(self,server1,password1):
        self.server1 = server1
        self.password1 = password1
        self.ssh = SSHClient()
        self.chan = None
        self.connect()

    def connect(self):#connect to the first One ( server1 )
        self.ssh.set_missing_host_key_policy(AutoAddPolicy())
        self.ssh.connect(self.server1, username='USERNME', password='PASS')
        self.chan = self.ssh.invoke_shell()

    def sendCMD(self,cmd,endswith):
        if cmd[-1]!='\n':
            cmd+='\n'
        buff = ''
        while not buff.endswith(endswith):
            resp = self.chan.recv(9999)
            buff += str(resp.decode())
            print(buff)
        self.chan.send(cmd)
        return buff

    def getBuffer(self,ends='> '):
        buff = ''
        while not buff.endswith(ends):
            resp = self.chan.recv(9999)
        buff+= resp.decode()
        return buff

    def close(self):
        self.ssh.close()

then you can create an SSHObject with:

ssh = SShCmd('serverA','passwordA')
ssh.sendCMD('ssh serverB\n','USERNAME> ')
#ssh.sendCMD('yes\n','(yes/no)? ')#if shh fingerprint don't exist
ssh.sendCMD('passwordB.\n','password: ')
ssh.sendCMD('YOUR COMMAND HERE.\n','USERNAME> ')
ssh.close()
Dharman
  • 30,962
  • 25
  • 85
  • 135
év3v
  • 26
  • 4
  • Why? Paramiko has native support for portforwarding/tunneling. – Martin Prikryl Feb 24 '22 at 14:39
  • @MartinPrikryl ,you can find the documentation of paramiko here: [link](https://docs.paramiko.org/en/stable/index.html) For my example paramiko is used for execute command, so I can execute any command as an SSH connection. – év3v Feb 25 '22 at 08:04