lxc-start-ephemeral: Use attach

With this change, systems that support it will use attach to run any
provided command.

This doesn't change the default behaviour of attaching to tty1, but it
does make it much easier to script or even get a quick shell with:
lxc-start-ephemeral -o p1 -n p2 -- /bin/bash

I'm doing the setgid,initgroups,setuid,setenv magic in python rather
than using the attach_wait parameters as I need access to the pwd module
in the target namespace to grab the required information.

Signed-off-by: Stéphane Graber <stgraber@ubuntu.com>
Acked-by: Serge E. Hallyn <serge.hallyn@ubuntu.com>
This commit is contained in:
Stéphane Graber 2014-02-13 12:42:21 -05:00
parent 5693029730
commit 8158c057dc

View File

@ -33,6 +33,7 @@ import argparse
import gettext import gettext
import lxc import lxc
import os import os
import pwd
import sys import sys
import subprocess import subprocess
import tempfile import tempfile
@ -77,10 +78,11 @@ parser.add_argument("--bdir", "-b", type=str,
help=_("directory to bind mount into container")) help=_("directory to bind mount into container"))
parser.add_argument("--user", "-u", type=str, parser.add_argument("--user", "-u", type=str,
help=_("the user to connect to the container as")) help=_("the user to run the command as"))
parser.add_argument("--key", "-S", type=str, parser.add_argument("--key", "-S", type=str,
help=_("the path to the SSH key to use to connect")) help=_("the path to the key to use to connect "
"(when using ssh)"))
parser.add_argument("--daemon", "-d", action="store_true", parser.add_argument("--daemon", "-d", action="store_true",
help=_("run in the background")) help=_("run in the background"))
@ -297,18 +299,40 @@ if not ips:
dest.destroy() dest.destroy()
sys.exit(1) sys.exit(1)
# NOTE: To replace by .attach() once the kernel supports it if os.path.exists("/proc/self/ns/pid"):
cmd = ["ssh", def attach_as_user(command):
try:
username = "root"
if args.user:
username = args.user
user = pwd.getpwnam(username)
os.setgid(user.pw_gid)
os.initgroups(user.pw_name, user.pw_gid)
os.setuid(user.pw_uid)
os.chdir(user.pw_dir)
os.environ['HOME'] = user.pw_dir
except:
print(_("Unable to switch to user: %s" % username))
sys.exit(1)
return lxc.attach_run_command(command)
retval = dest.attach_wait(attach_as_user, args.command,
env_policy=lxc.LXC_ATTACH_CLEAR_ENV)
else:
cmd = ["ssh",
"-o", "StrictHostKeyChecking=no", "-o", "StrictHostKeyChecking=no",
"-o", "UserKnownHostsFile=/dev/null"] "-o", "UserKnownHostsFile=/dev/null"]
if args.user: if args.user:
cmd += ["-l", args.user] cmd += ["-l", args.user]
if args.key: if args.key:
cmd += ["-i", args.key] cmd += ["-i", args.key]
for ip in ips: for ip in ips:
ssh_cmd = cmd + [ip] + args.command ssh_cmd = cmd + [ip] + args.command
retval = subprocess.call(ssh_cmd, universal_newlines=True) retval = subprocess.call(ssh_cmd, universal_newlines=True)
if retval == 255: if retval == 255: