Centos设置开机自动启动
Centos设置开机自动启动
利用systemd服务实现开机自动启动
- 创建配置文件
vim /etc/systemd/system/hello.service
### 文件内容
[Unit]
Description=Hello
[Service]
ExecStart=/usr/bin/python /root/hello.py
Restart=on-failure
[Install]
WantedBy=multi-user.target - 创建 python 脚本文件
vim /root/hello.py
### 脚本内容
import logging
import time
logging.basicConfig(format='Date-Time : %(asctime)s : Line No. : %(lineno)d - %(message)s', level = logging.DEBUG)
while True:
logging.debug("A Debug logging Message")
time.sleep(10) - 启动服务,并设置开机自启
systemctl daemon-reload # 编写后需要重新加载新的配置文件
systemctl start hello.service #启动服务
systemctl enable hello.service #设置开机自动启动
systemctl status hello.service #查看状态
[root@www ~]# systemctl status hello.service -l
● hello.service - Hello
Loaded: loaded (/etc/systemd/system/hello.service; enabled; vendor preset: disabled)
Active: active (running) since Sun 2024-04-14 11:27:37 CST; 2min 17s ago
Main PID: 8128 (python)
CGroup: /system.slice/hello.service
└─8128 /usr/bin/python /root/hello.py
Apr 14 11:28:17 www.a.org python[8128]: Date-Time : 2024-04-14 11:28:17,540 : Line No. : 5 - A Debug logging Message
Apr 14 11:28:27 www.a.org python[8128]: Date-Time : 2024-04-14 11:28:27,549 : Line No. : 5 - A Debug logging Message
Apr 14 11:28:37 www.a.org python[8128]: Date-Time : 2024-04-14 11:28:37,580 : Line No. : 5 - A Debug logging Message
Apr 14 11:28:47 www.a.org python[8128]: Date-Time : 2024-04-14 11:28:47,612 : Line No. : 5 - A Debug logging Message
Apr 14 11:28:57 www.a.org python[8128]: Date-Time : 2024-04-14 11:28:57,619 : Line No. : 5 - A Debug logging Message
Apr 14 11:29:07 www.a.org python[8128]: Date-Time : 2024-04-14 11:29:07,638 : Line No. : 5 - A Debug logging Message
Apr 14 11:29:17 www.a.org python[8128]: Date-Time : 2024-04-14 11:29:17,642 : Line No. : 5 - A Debug logging Message
Apr 14 11:29:27 www.a.org python[8128]: Date-Time : 2024-04-14 11:29:27,701 : Line No. : 5 - A Debug logging Message
Apr 14 11:29:37 www.a.org python[8128]: Date-Time : 2024-04-14 11:29:37,728 : Line No. : 5 - A Debug logging Message
Apr 14 11:29:47 www.a.org python[8128]: Date-Time : 2024-04-14 11:29:47,737 : Line No. : 5 - A Debug logging Message
systemctl restart hello #重启服务
ps aux | grep hello #查看进程
[root@www ~]# ps aux | grep hello
root 8347 0.0 0.2 138728 5404 ? Ss 11:31 0:00 /usr/bin/python /root/hello.py
root 8373 0.0 0.0 112812 976 pts/0 S+ 11:31 0:00 grep --color=auto hello
systemctl stop hello #停止服务
利用rc.local文件实现开机自启
- 添加启动命令
vim /etc/rc.d/rc.local
添加
/bin/echo ddd > /root/ddd.txt - 为rc.local添加执行权限
chmod +x /etc/rc.d/rc.local
- 重启计算机,相应的程序就会执行了。
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 哆啦酱的点心屋!
评论