Linux 服务自启动
-
在/lib/systemd/system创建*.service文件(这里创建agent.service),简单内容如下:
[Unit] Description = agent # 服务介绍 [Service] User=root # 以哪一个用户启动 Type=simple #启动模式 PIDFile=/run/agent.pid # 保存进程信息的文件 ExecStart=/root/work/python/Wappalyzer/dist/bin/agent # 需启动的服务的位置 ExecReload=/bin/kill -SIGHUP # 重启服务 ExecStop=/bin/kill -SIGINT # 停止服务 Restart=on-failure # 程序意外停止后自动重启,可用kill验证 RestartSec=30 # 重启时需要等待的秒数 [Install] WantedBy = multi-user.target #启动时,这个服务需要被自动运行。
-
注意(坑):
- ExecStart必须为绝对路径。
- 当ExecStart指向启动服务的脚本时,需要注意脚本中的文件路径,做好全用绝对路径。
- 当ExecStart指向启动服务的脚本时,脚本中直接用:/root/work/python/Wappalyzer/dist/bin/agent >log.txt 2>&1, 切勿使用:nohup /root/work/python/Wappalyzer/dist/bin/agent >log.txt 2>&1 &, 否则服务启动会报错。
-
-
刷新守护进程:
systemctl daemon-reload
-
设置自启动:
systemctl enable /lib/systemd/system/agent.service
设置成功会提示:Created symlink /etc/systemd/system/multi-user.target.wants/agent.service → /lib/systemd/system/agent.service.
-
启动服务:
systemctl start agent
-
重启服务:
systemctl restart agent
-
停止服务服务:
systemctl stop agent
-
查看自启服务状态:
systemctl status agent
-
查看自启服务日志:
journalctl -u agetn
-
查看服务列表:
systemctl list-unit-files # 所有服务 systemctl list-unit-files | grep anable # 自启服务
-
关闭自启服务:
systemctl disable agent systemctl daemon-reload
自动添加自启动服务脚本:
app_path="$PWD/agent" # 添加需要设置自启动的服务文件绝对路径,可多个
for a in $app_path; do
if [ ! -x $a ]; then
chmod +x $a
fi
sh_name=${a##*/}
app_sh="$PWD/bin/$sh_name"
if [ -f $app_sh ]; then
rm $app_sh
echo "rm $app_sh"
fi
echo "#! /bin/bash" >> $app_sh
echo "cd ${a%/*}" >> $app_sh
echo "$a >$PWD/log/${sh_name}_log.txt 2>&1" >> $app_sh
chmod +x $app_sh
service_sh="/lib/systemd/system/${sh_name}.service"
if [ -f $service_sh ]; then
systemctl disable $service_sh
rm $service_sh
systemctl daemon-reload
fi
echo "[Unit]" >> $service_sh
echo "Description = $sh_name" >> $service_sh
echo "[Service]" >> $service_sh
echo "User=root" >> $service_sh
echo "Type=simple" >> $service_sh
echo "PIDFile=/run/${sh_name}.pid" >> $service_sh
echo "ExecStart=$app_sh" >> $service_sh
echo "ExecReload=/bin/kill -SIGHUP $MAINPID" >> $service_sh
echo "ExecStop=/bin/kill -SIGINT $MAINPID" >> $service_sh
echo "Restart=on-failure" >> $service_sh
echo "RestartSec=30" >> $service_sh
echo "[Install]" >> $service_sh
echo "WantedBy = multi-user.target" >> $service_sh
systemctl daemon-reload
systemctl enable $service_sh
systemctl start $sh_name
done