如何使用pexpect处理SSHsession?

2024-04-27 04:12:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试自动化一个需要几个步骤的小任务,其中一些步骤对于所有“设备”都是相同的: -ssh登录 -运行命令 -清理干净

我有一个使用pexpect的脚本,但是对于每个函数(任务),我都必须建立SSH连接,这很糟糕。在

我想做的就是这样:

创建会话的函数和使用同一“子”的另一个函数

def ssh_login(device):
    child.spawn("ssh root@"+device)
    child.expect("password:")
    child.sendline(password)
    child.expect("#")

另一个使用会话并运行命令的函数

^{pr2}$

还有一个清理功能

def cleanup():
    child.sendline(cleanup)
    child.expect("#")
    child.sendline("exit")
    child.interract()

有什么想法吗?在


Tags: 函数命令脚本childdevicedef步骤login
2条回答

当我使用python和SSH做任何事情时,我都会使用Paramiko,这是一个非常可靠的模块,下面是我对任何使用它的项目的“入门代码”。我已经对它进行了参数化处理,并添加了一些注释,您可能希望生成一个要在其上运行该命令的服务器的列表,然后遍历它。不过,如果您需要在许多服务器上频繁地运行命令,可以考虑使用Saltstack或Ansible之类的工具,这样可以很容易地定期管理服务器。在

https://saltstack.com/

https://www.ansible.com/

 #!/usr/bin/env python

    import paramiko


    def run_ssh_cmd(remote_server, connect_user, identity, cmd=None):
        """ create an ssh connection to the remote server and retrieve
        information"""

        # kludge to make ssh work - add 'your_domain.com' to the remote_server
        remote_server += '.your_domain.com'

        client = paramiko.SSHClient()
        client.load_system_host_keys()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        client.connect(remote_server, username=connect_user, key_filename=identity)
        command_str = cmd
        stdin, stdout, stderr = client.exec_command(command_str)

        print stdout.readlines()
        client.close()

    if __name__ == '__main__':
        import sys
        import argparse
        import datetime

        parser = argparse.ArgumentParser()

        parser.add_argument("-s", " server", action="store", required=True,
                            dest="server", help="Server to query")
        parser.add_argument("-u", " user", action="store", required=True,
                            dest="user", help="User ID for remote server connection")
        parser.add_argument("-i", " identity", action="store", required=True,
                            dest="id_file", help="SSH key file")
        args = parser.parse_args()

        run_ssh_cmd(args.server, args.user, args.id_file, "hostname;date")

像这样:

pexpect.spawn('ssh', [ '-o' + 'ControlMaster=auto',username + "@" + hostname, '-o' + 'ControlPath=~/.ssh/master-%r@%h:%p'])

你会发现会话:

^{pr2}$

相关问题 更多 >