没有root/sudo如何运行系统服务

时间:2020-02-23 14:38:59  来源:igfitidea点击:

SystemD是一种现代系统的Sysv-Syly init和RC更换,适用于Linux系统,它利用了许多现代Linux内核功能。
它提供了一个作为PID 1运行的系统和服务管理器,并启动系统的其余部分。
SystemD是控制如何在现代Linux发行版启动,停止,重新启动和否则管理的服务的启动,停止,重新启动和否则管理的原因。

使用Linux系统或者由第三方应用程序安装的标准Systemd服务单元文件通常以root或者系统用户帐户运行。
本教程将向我们展示如何在没有Root的情况下运行SystemD服务,作为登录系统的标准用户。

系统服务单位

系统文件单元包含描述本机并定义其行为的配置指令。
在本教程中,我们将编写一个系统文件,可以在没有sudo的情况下登录用户管理。

运行SystemD服务作为标准登录用户

如果要将完全所有权与普通用户具有完全所有权,则应将用户Systemd服务放在~/.config/systemd/user /目录中。
如果不存在,创建它。

mkdir -p  ~/.config/systemd/user/

我们将创建一个运行句子应用程序的测试服务。

curl -s https://api.github.com/repos/syncthing/syncthing/releases/latest | grep browser_download_url | grep linux-amd64 | cut -d '"' -f 4 | wget -qi 
tar xvf syncthing-linux-amd64*.tar.gz
sudo cp syncthing-linux-amd64-*/syncthing  /usr/local/bin/

让我们确认我们的应用程序二进制。

$syncthing --version
syncthing v1.4.0 "Fermium Flea" (go1.13.8 linux-amd64) Hyman@theitroad 2017-03-06 19:52:22 UTC

在目录下创建一个系统服务单元文件。

$vim  ~/.config/systemd/user/syncthing.service
[Unit]
Description=Syncthing - Open Source Continuous File Synchronization
Documentation=man:syncthing(1)
[Service]
ExecStart=/usr/local/bin/syncthing -no-browser -no-restart -logflags=0
Restart=on-failure
SuccessExitStatus=3 4
RestartForceExitStatus=3 4
# Hardening
SystemCallArchitectures=native
MemoryDenyWriteExecute=true
NoNewPrivileges=true
[Install]
WantedBy=default.target

重新加载系统。

$systemctl --user daemon-reload

确认服务可用。

$systemctl --user list-unit-files syncthing.service
UNIT FILE         STATE   
syncthing.service disabled
1 unit files listed.

我们可以在创建后启动该服务。

$systemctl --user enable --now syncthing.service
Created symlink /home/vagrant/.config/systemd/user/default.target.wants/syncthing.service → /home/vagrant/.config/systemd/user/syncthing.service.

让我们检查我们的服务状态。

$systemctl --user status syncthing.service 
● syncthing.service - Syncthing - Open Source Continuous File Synchronization
   Loaded: loaded (/home/vagrant/.config/systemd/user/syncthing.service; enabled; vendor preset: enabled)
   Active: active (running) since Fri 2017-04-03 17:18:54 UTC; 5s ago
     Docs: man:syncthing(1)
 Main PID: 22628 (syncthing)
   CGroup: /user.slice/user-1000.slice/Hyman@theitroad/syncthing.service
           ├─22628 /usr/local/bin/syncthing -no-browser -no-restart -logflags=0
           └─22632 /usr/local/bin/syncthing -no-browser -no-restart -logflags=0

使用的选项是:-User - 连接到用户服务管理器