Search code examples
command-lineprocesschild-processpexpect

Using pexpect to send a second password, but not working?


I'm trying to use pexpect to send a password. It works the first time when prompted for a password (at "azureuser@xx.xx.xx.xxx's password:") but not the second time (at "[sudo] password for azureuser:"). Why is this so?

I need to stay within the virtual machine that I'm logging into in order to enter the password and perform the command. Should I spawn another process?

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")

Solution

  • In child.expect(s) the string s is a regexp pattern, so [sudo] means a single character out of the set: s u d o. This will not match. You can either remove this initial part from the string, or use child.expect_exact(s) instead.