9

Assuming a modern Linux host, is there any convenient way to spawn an interactive shell in the exact context systemd would use for a unit/service?

Alternatively, any way to attach a shell to a running process started by systemd?

The goal is to interactively test restrictions and capabilities, starting env, working path, etc.

3 Answers 3

16

systemd v258 added a new unit-shell verb to the systemd-analyze command that does exactly this:

systemd-analyze unit-shell SERVICE [command...]

The given command runs on the namespace of the specified running service. If no command is given, spawn and attach a shell with the namespace to the service.

Demonstration:

# cat <<EOF > /etc/systemd/system/my-test-unit.service [Service] Type=exec ExecStart=/usr/bin/sleep infinity TemporaryFileSystem=/etc/ BindPaths=/usr/lib/systemd/systemd:/etc/some-folder/some-file EOF # systemctl daemon-reload && systemctl restart my-test-unit.service # /etc/some-folder/some-file --version bash: /etc/some-folder/some-file: No such file or directory # systemd-analyze unit-shell my-test-unit.service > /etc/some-folder/some-file --version systemd 258 (258.2-1.fc43) +PAM +AUDIT +SELINUX -APPARMOR +IMA +IPE +SMACK +SECCOMP -GCRYPT +GNUTLS +OPENSSL +ACL +BLKID +CURL +ELFUTILS +FIDO2 +IDN2 -IDN -IPTC +KMOD +LIBCRYPTSETUP +LIBCRYPTSETUP_PLUGINS +LIBFDISK +PCRE2 +PWQUALITY +P11KIT +QRENCODE +TPM2 +BZIP2 +LZ4 +XZ +ZLIB +ZSTD +BPF_FRAMEWORK +BTF +XKBCOMMON +UTMP +SYSVINIT +LIBARCHIVE > exit # /etc/some-folder/some-file --version bash: /etc/some-folder/some-file: No such file or directory 

Note that systemd v258 was only released a few months ago (September 2025), so you'll probably have to wait a bit until this is available in whichever distro you use.

7

Use systemd-run with the properties copied out of the .service file into -p options. This will actually call into systemd to create a real in-memory .service unit, but with the additional possibility of getting an interactive tty attached:

systemd-run -p User=foo --pty /bin/bash 

(There may be a more convenient method to "enter" a whole .service in the future but I only vaguely remember seeing it mentioned in git.)

When bind mounts are used, attaching just to the mount namespace of a process (or a network namespace, etc) can be done using nsenter.

nsenter -a -t $PID -- findmnt 
0

documenting one way, not necessarily limited to systemd:

  1. start a listener on port 1234 nc -lnvp 1234
  2. edit the unit file to Exec: nc -e /bin/sh localhost 1234

Now when you start the service unit, it will connect to the listener and pass stdin/out to it. You can use the listener as a crude remote shell, and you will be sure the environment is the one for the process that would be in the unit file.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.