1

我在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功能。

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

4

1 回答 1

0

我查看了wexpect repo,处理logfile参数的唯一代码在遗留模块中(类中的read_nonblocking()andsend()方法),所以它现在spawn_windows看起来不像工作。logfile

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

笔记

  • 在 Windows 11 上测试,使用 Python 3.9 和 Parmiko 2.9
  • 添加aes256-cbc到我的远程虚拟机sshd_config以匹配您的连接。顺便说一句,您可以在Transport元组中放置多个密码,只要它们在两个设备上(我Get-TlsCipherSuite | Format-Table -Property CipherSuite, Name在 Windows 上使用)。
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.
于 2022-01-11T23:49:43.153 回答