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