使用 Paramiko 从远程服务器执行命令到另一个远程服务器 [英] Executing command from remote server into another remote server using Paramiko

查看:71
本文介绍了使用 Paramiko 从远程服务器执行命令到另一个远程服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试连接到一个特定的中央服务器,该服务器已配置到所有其他服务器的无密码连接,我目前所在的服务器无法访问我想要运行命令的服务器.所以我试图连接到中央服务器,然后从那里将 ssh 连接到我需要运行命令的其他服务器.当我在执行 ssh 命令后运行它时,程序被冻结并且不允许将命令执行到最终的远程服务器.在这种情况下,假设我想在最终服务器host.name"上运行 ifconfig.

I am trying to connect to a specific central server that has configured passwordless connection to all other servers, the server I am currently on has no access to the ones I want to run commands. So I am trying to connect to central server and from there do ssh into other servers I need to run commands. When I run this after I execute ssh command program gets frozen and does not allow to execute commands into final remote server. In this case let's say I want to run ifconfig on final server 'host.name'.

def get_host_info_linux(self,host,db_engine):
    #Create ssh client from paramiko library
    client = paramiko.SSHClient()

    try:
        # Connect to remote host
        #logger.info(username_pass)
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(hostname='tunel host name', username=f'{db_engine}')
        #this command is to do ssh into the server I want to execute commands
        ssh_cmd = f'ssh {host.name}'

        ssh_std = client.exec_command(ssh_cmd)
        if (ssh_std[2].readlines() == []):+

            logger.debug(ssh_std[1].readlines()[0])

        else:
            logger.error(ssh_std[2].readlines())

      client.exe_command('ifconfig')

    except Exception as e:
        logging.error(e)
    finally:
        client.close()

推荐答案

  • 通常要在只能通过另一个 SSH 服务器连接的服务器上执行命令,您应该使用端口转发:
    使用 Python Paramiko 的嵌套 SSH

    但是如果我理解正确的话,您不想从本地机器进行身份验证,因为您已经从跳转主机设置了身份验证(您是否在跳转主机上存储了私钥?) 在这种情况下,您需要:
    在 Python Paramiko 中的 SSH 服务器上的辅助 shell/命令中执行(子)命令.或者您可以将密钥从跳转主机带到本地机器.请参阅具有 RSA 密钥文件的嵌套 SSH.

    But if I understood correctly, you do not want to authenticate from the local machine, as you have the authentication set up from the jump host (do you have a private key stored on the jump host?) In that case, you want this:
    Execute (sub)commands in secondary shell/command on SSH server in Python Paramiko. Or you can bring the key from the jump host to the local machine. See Nested SSH with RSA key file.

    虽然不是通过重定向输入将命令提供给 ssh,您也可以使用 ssh 命令行作为更标准化的接口:

    Though instead of feeding the commands to ssh via a redirected input, you might also use ssh command line as a more standardized interface:

    ssh destination command
    

  • 这篇关于使用 Paramiko 从远程服务器执行命令到另一个远程服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆