-2

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")
greendaysbomb
  • 364
  • 2
  • 6
  • 23

1 Answers1

0

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.

meuh
  • 11,500
  • 2
  • 29
  • 45
  • Oh thank you! Such a simple fix that I overlooked. I removed `[sudo]` and it works just fine now, but thanks for telling me about the `.expect_exact(s)` command as well. – greendaysbomb Jun 06 '21 at 11:48