This repository has been archived by the owner on Aug 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 385
/
enter-systemd-namespace
executable file
·51 lines (45 loc) · 1.79 KB
/
enter-systemd-namespace
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/bin/bash --norc
if [ "$LOGNAME" != "root" ]; then
echo "You need to run $0 through sudo"
exit 1
fi
if [ -x /usr/sbin/daemonize ]; then
DAEMONIZE=/usr/sbin/daemonize
elif [ -x /usr/bin/daemonize ]; then
DAEMONIZE=/usr/bin/daemonize
else
echo "Cannot execute daemonize to start systemd."
exit 1
fi
if ! command -v /lib/systemd/systemd > /dev/null; then
echo "Cannot execute /lib/systemd/systemd."
exit 1
fi
if ! command -v /usr/bin/unshare > /dev/null; then
echo "Cannot execute /usr/bin/unshare."
exit 1
fi
SYSTEMD_EXE="/lib/systemd/systemd --unit=basic.target"
SYSTEMD_PID="$(ps -eo pid=,args= | awk '$2" "$3=="'"$SYSTEMD_EXE"'" {print $1}')"
if [ -z "$SYSTEMD_PID" ]; then
"$DAEMONIZE" /usr/bin/unshare --fork --pid --mount-proc bash -c 'export container=wsl; mount -t binfmt_misc binfmt_misc /proc/sys/fs/binfmt_misc; exec '"$SYSTEMD_EXE"
while [ -z "$SYSTEMD_PID" ]; do
echo "Sleeping for 1 second to let systemd settle"
sleep 1
SYSTEMD_PID="$(ps -eo pid=,args= | awk '$2" "$3=="'"$SYSTEMD_EXE"'" {print $1}')"
done
fi
USER_HOME="$(getent passwd | awk -F: '$1=="'"$SUDO_USER"'" {print $6}')"
if [ -n "$SYSTEMD_PID" ] && [ "$SYSTEMD_PID" != "1" ]; then
if [ -n "$1" ] && [ "$1" != "bash --login" ] && [ "$1" != "/bin/bash --login" ]; then
exec /usr/bin/nsenter -t "$SYSTEMD_PID" -a \
/usr/bin/sudo -H -u "$SUDO_USER" \
/bin/bash -c 'set -a; [ -f "$HOME/.systemd-env" ] && source "$HOME/.systemd-env"; set +a; exec bash -c '"$(printf "%q" "$@")"
else
exec /usr/bin/nsenter -t "$SYSTEMD_PID" -a \
/bin/login -p -f "$SUDO_USER" \
$([ -f "$USER_HOME/.systemd-env" ] && /bin/cat "$USER_HOME/.systemd-env" | xargs printf ' %q')
fi
echo "Existential crisis"
exit 1
fi