登录 主页

Linux 使用systemd service 实现开机自启动

2024-03-22 04:32PM

参考:

https://linlin.fun/blogs/1113

https://blog.csdn.net/dreamstar613/article/details/124063201

1. 创建一个 $ sudo vim /etc/systemd/system/myservice.service 文件

myservice.service 替换为你要创建自启动的文件名:

内容如下:

[Unit]
Description=My Service
After=network.target

[Service]
ExecStart=/path/to/your/service
Type=simple

[Install]
WantedBy=multi-user.target

eg:我要设置trojan在开机时自启动

创建 $ sudo vim /etc/systemd/system/trojan.service 文件

[Unit]
Description=My Service Start Trojan
After=network.target

[Service]
WorkingDirectory=/home/meiyi/Downloads/trojan
ExecStart=/home/meiyi/Downloads/trojan/trojan
Type=simple

[Install]
WantedBy=multi-user.target 

 然后保存文件

2. 重新加载:

meiyi@meiyi-Extensa-2511G:/etc/systemd/system$ sudo systemctl daemon-reload

3. 启动

meiyi@meiyi-Extensa-2511G:/etc/systemd/system$ sudo systemctl enable trojan
Created symlink /etc/systemd/system/multi-user.target.wants/trojan.service → /etc/systemd/system/trojan.service. 

这表示trojan服务已成功启用。你看到的输出信息表明/etc/systemd/system/multi-user.target.wants/目录下创建了一个符号链接,指向/etc/systemd/system/trojan.service文件。这意味着当系统启动到multi-user.target目标时,trojan服务将会自动启动。 

手动启动:

meiyi@meiyi-Extensa-2511G:/etc/systemd/system$ sudo systemctl start trojan

手动停止:

meiyi@meiyi-Extensa-2511G:/etc/systemd/system$ sudo systemctl stop trojan 

重启:

meiyi@meiyi-Extensa-2511G:/etc/systemd/system$ sudo systemctl restart trojan 

查看状态:

meiyi@meiyi-Extensa-2511G:/etc/systemd/system$ sudo systemctl status trojan
● trojan.service - My Service Start Trojan
     Loaded: loaded (/etc/systemd/system/trojan.service; enabled; vendor preset: enabled)
     Active: active (running) since Fri 2024-03-22 16:24:40 CST; 1s ago
   Main PID: 3195472 (trojan)
      Tasks: 1 (limit: 18995)
     Memory: 636.0K
        CPU: 6ms
     CGroup: /system.slice/trojan.service
             └─3195472 /home/meiyi/Downloads/trojan/trojan

3月 22 16:24:40 meiyi-Extensa-2511G systemd[1]: Started My Service Start Trojan.
3月 22 16:24:40 meiyi-Extensa-2511G trojan[3195472]: Welcome to trojan 1.16.0
3月 22 16:24:40 meiyi-Extensa-2511G trojan[3195472]: [2024-03-22 16:24:40] [WARN] trojan service (client) started at 127.0.0.1:1090 

 然后就可以了。

返回>>

登录

请登录后再发表评论。

评论列表:

目前还没有人发表评论