0

I want to start an lxc with sudo lxc-start -n <lxc-name> --lxcpath=/some/custom/path in a python script and controll it with pexpect (login, install a package, add a user and logout/shutdown the lxc). An example would look like this (I'm pretty close to the solution, just need the right escape_character argument for pexpect.spawn.interact):

import pexpect
child = pexpect.spawn("sudo lxc-start --name=debian-wheezy-amd64 --lxcpath=/some/custom/path/")
child.expect("Password:") # the sudo password prompt (might be optional if the script has been invoked with sudo (let's keep in anyway as an exercise))
child.interact("??") # tried "\r" -> never returns, "\r\r" and "\n" -> accepts the sudo password, but doesn't give back the control to the python interpreter (stuck at lxc login)
child.expect("login")
child.sendline("root")
# etc. (tasks mentioned above)
child.expect("[#$][\\s]")
child.sendline("shutdown -h 0")

Everythings works well if I enter the password with getpassword, store it in a variable and pass it with child.expect("Password:"); child.sendline(mypassword), so the solution above is rather an exercise for better understanding of pexpect.

Is there a generic escape_character for all OSs/lxcs to enter the sudo password or do they differ (and if they do is there a generic way to determine them independent of the knowledge about the OS (e.g. with a shell variable)?)

Kalle Richter
  • 8,008
  • 26
  • 77
  • 177
  • Are you looking for an escape character that can't be in the sudo password that you can use to indicate that interaction is done and the script should continue? – Thomas K Jun 02 '14 at 17:49
  • @ThomasK I want to restrict the interactive mode to the entering of the password and leave it afterwards. If the escape character is considered part of the sudo password (I don't know how sudo handles `\n`, `\r` and `\x1d`) or of input in general (recognized by `pexpect`) isn't important. – Kalle Richter Jun 02 '14 at 21:35
  • The escape character isn't sent through to the child process, so if you make it something like `\n`, pressing enter will stop interaction mode without submitting the password. You could probably do it by making `\n` the escape character, and then doing `child.sendline()` immediately after interact. – Thomas K Jun 02 '14 at 23:36

0 Answers0