一、需求背景
存在某台服务器,设置某服务开机自启后无法生效,故需要在开机后手动执行命令启动,操作比较繁琐,采用自动化脚本方式实现。
二、编写系统启动单元
vim /etc/systemd/system/restart-yl.service
[Unit]
Description=YL
After=network.target
[Service]
ExecStart=/bin/systemctl restart YL.service
Type=oneshot
RemainAfterExit=yes
[Install]
WantedBy=multi-user.target
保存文件并退出文本编辑器。
三、重载并使其生效
重新加载systemd配置以使其了解新服务:
systemctl daemon-reload
启用该服务以在启动时运行:
systemctl enable restart-yl.service
[root@localhost ~]# systemctl enable restart-ylmonitor.service
Created symlink /etc/systemd/system/multi-user.target.wants/restart-ylmonitor.service → /etc/systemd/system/restart-ylmonitor.service.
[root@localhost ~]# systemctl status restart-ylmonitor.service
● restart-ylmonitor.service - YLMonitor
Loaded: loaded (/etc/systemd/system/restart-ylmonitor.service; enabled; vendor preset: disable>
Active: inactive (dead)
[root@localhost ~]# systemctl start restart-ylmonitor.service
[root@localhost ~]# systemctl status restart-ylmonitor.service
● restart-ylmonitor.service - YLMonitor
Loaded: loaded (/etc/systemd/system/restart-ylmonitor.service; enabled; vendor preset: disable>
Active: active (exited) since Mon 2023-09-11 10:43:31 CST; 2s ago
Process: 3276910 ExecStart=/bin/systemctl restart YLMonitor.service (code=exited, status=0/SUCC>
Main PID: 3276910 (code=exited, status=0/SUCCESS)
9月 11 10:43:31 localhost.localdomain systemd[1]: Starting YLMonitor...
9月 11 10:43:31 localhost.localdomain systemd[1]: Started YLMonitor.
[root@localhost ~]# systemctl status YLMonitor
● YLMonitor.service - YLMonitor service
Loaded: loaded (/etc/systemd/system/YLMonitor.service; enabled; vendor preset: disabled)
Active: active (running) since Mon 2023-09-11 10:43:31 CST; 32s ago
Main PID: 3276925 (YLMonitor)
Tasks: 11 (limit: 201980)
Memory: 7.6M
CGroup: /system.slice/YLMonitor.service
└─3276925 /temp/YLMonitor/YLMonitor -c /temp/YLMonitor/YLMonitor.ini
9月 11 10:43:31 localhost.localdomain systemd[1]: Started YLMonitor service.
9月 11 10:43:31 localhost.localdomain YLMonitor[3276925]: 2023/09/11 10:43:31 [I] [root.go:220] s>
9月 11 10:43:31 localhost.localdomain YLMonitor[3276925]: 2023/09/11 10:43:31 [I] [service.go:301>
9月 11 10:43:31 localhost.localdomain YLMonitor[3276925]: 2023/09/11 10:43:31 [I] [proxy_manager.>
9月 11 10:43:31 localhost.localdomain YLMonitor[3276925]: 2023/09/11 10:43:31 [I] [control.go:172>