【问题标题】:How do you ssh into a remote host through a jump host and execute multiple commands? [duplicate]如何通过跳转主机 ssh 进入远程主机并执行多个命令? [复制]
【发布时间】:2022-02-24 22:29:19
【问题描述】:

我正在寻找一个需要执行以下操作的 python 脚本:

  1. SSH 到主机 A
  2. 从主机 A,SSH 到主机 B(主机 B 只能从主机 A 连接)
  3. 从主机 B,执行命令集并在屏幕上显示输出

有人可以就如何实现这一点提出建议吗?

【问题讨论】:

  • 到目前为止你有什么尝试?
  • 你需要先用命令完成同样的任务(ssh port-forward是一种解决方案),理解机制,然后尝试python。
  • 这里的答案可能会有所帮助 - stackoverflow.com/questions/8169739/…
  • 这基本上就是-J 选项的用途。从您的角度来看,您只需从本地主机连接到 B,告诉ssh“使用”主机 A 这样做。

标签: python ssh paramiko


【解决方案1】:

我对 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()

然后你可以创建一个 SSHObject:

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()

【讨论】:

  • 为什么? Paramiko 原生支持端口转发/隧道。
  • @MartinPrikryl ,你可以在这里找到 paramiko 的文档:link 我的例子 paramiko 用于执行命令,所以我可以执行任何命令作为 SSH 连接。
猜你喜欢
  • 2021-11-26
  • 1970-01-01
  • 2018-08-27
  • 1970-01-01
  • 2016-07-26
  • 1970-01-01
  • 2012-01-12
  • 2012-05-06
  • 2019-08-09
相关资源
最近更新 更多