首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用pexcept发送本地和远程命令?

如何使用pexcept发送本地和远程命令?
EN

Stack Overflow用户
提问于 2021-04-23 03:58:53
回答 1查看 91关注 0票数 1

我有一个简单的类,允许我发送大量本地CLI命令。允许我测试某些命令行函数。这种机制运作得很好,但还需要扩展。我很难理解如何改变这种机制来处理本地或远程命令。

代码语言:javascript
复制
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

返回如下内容:

代码语言:javascript
复制
username (root):yourUN
password:*****
Logged in user yourUN

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

我已经设置我的测试机器允许远程SSH没有用户SSH登录。

EN

回答 1

Stack Overflow用户

发布于 2021-12-10 04:16:55

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

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

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."错误。

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

以下是完整的代码:

注意到在Linux5.14.16上使用Python3.9进行了测试。远程机器是Ubuntu8.04。

代码语言:javascript
复制
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.")

输出:

代码语言:javascript
复制
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.
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67223821

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档