no sudo inside

This commit is contained in:
Andrew Hurley 2026-07-05 17:19:46 +08:00
parent 4e39381b83
commit 1a5ac06ec0
1 changed files with 5 additions and 23 deletions

28
lxcd.py
View File

@ -1,6 +1,5 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import argparse import argparse
import grp
import os import os
import re import re
import subprocess import subprocess
@ -117,19 +116,6 @@ def detect_timezone():
def detect_locale(): def detect_locale():
return os.environ.get("LANG", "en_US.UTF-8") return os.environ.get("LANG", "en_US.UTF-8")
def lxc_prefix():
"""Return [] if running inside a Snap, or if the user is root or in the lxd group."""
if os.environ.get("SNAP"):
return []
if os.getuid() == 0:
return []
try:
if grp.getgrnam("lxd").gr_gid in os.getgroups():
return []
except KeyError:
pass
return ["sudo"]
def run_cmd(cmd, check=True): def run_cmd(cmd, check=True):
"""Helper to run shell commands.""" """Helper to run shell commands."""
try: try:
@ -139,15 +125,15 @@ def run_cmd(cmd, check=True):
sys.exit(e.returncode) sys.exit(e.returncode)
def lxc_run(args, check=True): def lxc_run(args, check=True):
"""Run an lxc command via run_cmd, auto-adding sudo if needed.""" """Run an lxc command via run_cmd."""
cmd = [*lxc_prefix(), "lxc", *args] cmd = ["lxc", *args]
if VERBOSE: if VERBOSE:
print(f"+ {' '.join(cmd)}", file=sys.stderr) print(f"+ {' '.join(cmd)}", file=sys.stderr)
return run_cmd(cmd, check=check) return run_cmd(cmd, check=check)
def lxc_subprocess(args, **kwargs): def lxc_subprocess(args, **kwargs):
"""Run an lxc command via subprocess.run, auto-adding sudo if needed.""" """Run an lxc command via subprocess.run."""
cmd = [*lxc_prefix(), "lxc", *args] cmd = ["lxc", *args]
if VERBOSE: if VERBOSE:
print(f"+ {' '.join(cmd)}", file=sys.stderr) print(f"+ {' '.join(cmd)}", file=sys.stderr)
return subprocess.run(cmd, **kwargs) return subprocess.run(cmd, **kwargs)
@ -357,7 +343,6 @@ def handle_enter(args):
if display: if display:
env_prefix += f"DISPLAY={display} " env_prefix += f"DISPLAY={display} "
prefix = lxc_prefix()
shell_cmd = "exec /bin/bash --login" shell_cmd = "exec /bin/bash --login"
exec_cmd = [ exec_cmd = [
"lxc", "exec", args.name, "lxc", "exec", args.name,
@ -368,10 +353,7 @@ def handle_enter(args):
"sh", "-c", f"env {env_prefix} sh -c '{shell_cmd}'" "sh", "-c", f"env {env_prefix} sh -c '{shell_cmd}'"
] ]
if prefix: os.execvp("lxc", exec_cmd)
os.execvp("sudo", ["sudo", *exec_cmd])
else:
os.execvp("lxc", exec_cmd)
def handle_stop(args): def handle_stop(args):
print(f"Stopping container '{args.name}'...") print(f"Stopping container '{args.name}'...")