【问题标题】:How do I use pexcept to send local AND remote commands如何使用 pexcept 发送本地和远程命令
【发布时间】:2021-04-23 03:58:53
【问题描述】:

我有一个简单的类,允许我发送大量本地 CLI 命令。允许我测试某些命令行功能。该机制运行良好,但需要扩展。我对如何更改此机制以处理本地或远程命令感到困惑。

from pexpect import *
class Expect( ):
    def Do( self, cmd, program: list = [], timeout = 20 ):
        result = run( cmd, events=program, timeout=timeout).decode() 
        return result

cmd  = 'login'
prog = [('username \\(.+\\):', 'yourUN\n'), ('password:', 'yourPW\n')]
res  = Expect().Do( cmd, prog )    # Returns everything
print( 'res: ' + res )
# use results to verify functionality

返回类似:

username (root):yourUN
password:*****
Logged in user yourUN

我目前有超过 1250 个测试运行大约 5000 个 cli 本地命令。唯一的问题是我需要这个类来支持本地命令以及远程 SSH 命令。

我已将我的测试机器设置为允许远程 SSH 而无需用户 SSH 登录。

【问题讨论】:

    标签: python-3.x pexpect


    【解决方案1】:

    如果我理解了这个问题,并且根据我的测试,您将需要两个函数或方法。

    1. 第一个函数使用 Pexpect 运行本地命令。您也可以使用第一个函数运行 ssh 命令,但前提是 IP 地址存在于 known_hosts 文件中:

    pexpect.run("ssh yourUN@192.168.x.x 'whoami'")

    否则,您将遇到"The authenticity of host '192.168.x.x (192.168.x.x)' can't be established." 错误。

    2.为避免该错误,我建议使用 Paramiko 的 ssh 命令使用第二个函数。

    完整代码如下:

    注意 - 使用 Python 3.9 在 Linux 5.14.16 上测试。远程机器是 Ubuntu 8.04。

    from getpass import getpass
    
    import paramiko
    import pexpect
    
    
    def run_cli_commands(list_of_commands, password=None):
        for c in list_of_commands:
            print("Command:", c)
            command_output, exitstatus = pexpect.run(
                c,
                events={"(?i)password": password if password is not None else getpass()},
                withexitstatus=True)
            print("Output:\n", command_output.decode())
    
    
    def run_ssh_commands(list_of_commands, ip_address, username, password):
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(ip_address, username=username, password=password)
        for c in list_of_commands:
            print("Command:", c)
            stdin, stdout, stderr = ssh.exec_command(c)
            print("Output:\n", stdout.read().decode())
    
    
    run_cli_commands(["which ssh",
                      "systemctl status ssh",
                      "systemctl start ssh",
                      "systemctl status ssh", ], password="**********")
    run_ssh_commands(["whoami",
                      "date", ], "192.168.x.x", "yourUN", "**********")
    run_cli_commands(["systemctl stop ssh", ], password="**********")
    print("Script complete. Have a nice day.")
    

    输出:

    Local command: which ssh
    Output:
     /usr/bin/ssh
    
    Local command: systemctl status ssh
    Output:
     ○ ssh.service - OpenBSD Secure Shell server
         Loaded: loaded (/lib/systemd/system/ssh.service; disabled; vendor preset: disabled)
         Active: inactive (dead)
           Docs: man:sshd(8)
                 man:sshd_config(5)
    
    Local command: systemctl start ssh
    Output:
     
    Local command: systemctl status ssh
    Output:
     ● ssh.service - OpenBSD Secure Shell server
         Loaded: loaded (/lib/systemd/system/ssh.service; disabled; vendor preset: disabled)
         Active: active (running) since Thu 2021-12-09 23:13:05 EST; 174ms ago
           Docs: man:sshd(8)
                 man:sshd_config(5)
        Process: 4565 ExecStartPre=/usr/sbin/sshd -t (code=exited, status=0/SUCCESS)
       Main PID: 4566 (sshd)
          Tasks: 1 (limit: 2275)
         Memory: 2.3M
            CPU: 18ms
         CGroup: /system.slice/ssh.service
                 └─4566 "sshd: /usr/sbin/sshd -D [listener] 0 of 10-100 startups"
    
    SSH command: whoami
    Output:
     yourUN
    
    SSH command: date
    Output:
     Thu Dec  9 23:13:04 EST 2021
    
    Local command: systemctl stop ssh
    Output:
     
    Script complete. Have a nice day.
    

    【讨论】:

      猜你喜欢
      • 2012-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-18
      相关资源
      最近更新 更多