需求
开机自动运行程序(或脚本),需要以root权限运行但不输入密码,也不能将密码写入文件。
环境
Ubuntu 20.04
解决方案
添加系统服务,然后通过systemctl控制。
操作步骤
假设目标程序为/home/xxx/test
1、创建service配置文件
[Unit]
Description=test
DefaultDependencies=no
#Before=cloud-init-local.service
After=vgauth.service
After=apparmor.service
#RequiresMountsFor=/tmp
After=systemd-remount-fs.service systemd-tmpfiles-setup.service systemd-modules-load.service
[Service]
ExecStart=/home/xxx/test
TimeoutStopSec=5
[Install]
WantedBy=multi-user.target
Alias=test
保存为test.service。
2、执行下面的命令安装
sudo cp ./test.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable test
3、重启,查看服务是否运行
sudo systemctl list-units |grep test
sudo systemctl list-unit-files |grep test