'How do you ssh into a remote host through a jump host and execute multiple commands? [duplicate]
Im looking to write a python script which need to perform the following:
- SSH into host A
- From host A, SSH into host B (host B can be connected only from host A)
- From host B, Execute set of commands and show the output on screen
Could someone please advise on how to achieve this?
Solution 1:[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()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dharman |
