【问题标题】:wexpect equivalent for logging我们期望等效于日志记录
【发布时间】:2022-01-11 19:17:31
【问题描述】:

我有以下代码在 linux 中使用 pexpect 没问题。

import pexpect 

child = pexpect.spawn('ssh test@ip' % (susername, ip) , encoding='utf-8')
child.logfile = open("{}/{}.txt".format(folder, ip),"w")

尝试更改为 wexpect 以在 windows 中使用但日志文件为空时 我的目标是将 wexpect 产生的所有内容从头到尾写入日志文件

我试过了

import wexpect

logging =""
child = wexpect.spawn('ssh -c aes256-cbc %s@%s' % (username, ip) , encoding='utf-8' , logfile=logging)
print(logging)
child.logfile = open("{}/{}.txt".format(folder, ip),"w")

但 print 也是空的。

所有其他wexpect 函数似乎都工作正常,我可以使用.sendline.expect 函数。

检查是否有人知道如何让日志记录工作 似乎没有很多文档

【问题讨论】:

    标签: python python-3.x pexpect wexpect


    【解决方案1】:

    我查看了wexpect repo,处理logfile 参数的唯一代码在legacy module 中(read_nonblocking()send() 方法在spawn_windows 类中),所以它没有t 看起来像 logfile 现在可以使用。

    我尝试了pexpect.popen_spawn.PopenSpawn,但我遇到了 SSH 问题。我可以建议你试试paramiko吗?

    注意

    • 在 Windows 11 上测试,使用 Python 3.9 和 Parmiko 2.9
    • 已将 aes256-cbc 添加到我的远程 VM 的 sshd_config 以匹配您的连接。顺便说一句,您可以在 Transport 元组中放置多个密码,只要它们在两个设备上(我在 Windows 上使用 Get-TlsCipherSuite | Format-Table -Property CipherSuite, Name)。
    import paramiko
    
    ip_address = "192.168.x.xxx"
    username = "stack"
    password = "**********"
    
    list_of_commands = ["which ssh", "date", "whoami", ]
    
    paramiko.Transport._preferred_ciphers = ("aes256-cbc", )
    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())
    print("Script complete. Have a nice day.")
    

    输出:

    Command: which ssh
    Output:
     /usr/bin/ssh
    
    Command: date
    Output:
     Tue 11 Jan 2022 06:36:34 PM EST
    
    Command: whoami
    Output:
     stack
    
    Script complete. Have a nice day.
    

    【讨论】:

    • 使用 pexpect 或 wexpect 模块的原因,我需要在输入下一个命令之前检测正则表达式返回字符串。 eg: show tech 需要很长时间才能完成运行才能进入下一个命令 感谢帮助推荐 paramiko
    猜你喜欢
    • 2014-09-08
    • 1970-01-01
    • 1970-01-01
    • 2011-02-02
    • 1970-01-01
    • 1970-01-01
    • 2017-06-26
    • 1970-01-01
    • 2023-02-06
    相关资源
    最近更新 更多