使用 pexpect 发送第二个密码,但不起作用?

问题描述

我正在尝试使用 pexpect 发送密码。当提示输入密码时(在 "azureuser@xx.xx.xx.xxx's password:"),它第一次起作用,但在第二次(在 "[sudo] password for azureuser:")时不起作用。为什么会这样?

我需要留在我登录的虚拟机中才能输入密码并执行命令。我应该生成一个进程吗?

import pexpect

def access_azure_vm(blob_name,src,dest):
    child = pexpect.spawn(key.SSH_KEY)
    child.logfile = sys.stdout.buffer
    child.expect("azureuser@xx.xx.xx.xxx's password:")
    child.sendline(key.PASSKEY)
    child.expect("azureuser@vm")
    # Run sudo azcopy copy <src> <dest>
    child.sendline('sudo azcopy copy ' + "\"" + src + "\"" + " " + "\"" + dest + blob_name + "\"" + " --recursive")
    child.expect("[sudo] password for azureuser:")
    child.sendline(key.PASSKEY)
    child.expect("azureuser@vm")

解决方法

child.expect(s) 中,字符串 s 是一个正则表达式模式,所以 [sudo] 表示集合中的单个字符:s u d o。这将不匹配。您可以从字符串中删除此初始部分,也可以改用 child.expect_exact(s)