Ubuntu 设置开机自启服务

目录


一、sh执行脚本创建

1.1、创建start.sh脚本

sudo vim start.sh

按i对将要编写的脚本语言进行编辑

如:

         Ubuntu 设置开机自启服务 

编辑完脚本之后,按esc键,输入“wq!”对文件进行保存

1.2、设置start.sh的读写权限

sudo chmod +777 start.sh

 

sudo chmod +644 start.sh

1.3、设置start.sh的格式

因为linux与windows的编辑格式不同,我们在后续运行start.sh可能会出现未预期的符号或者附近有语法错误,此时我们需要对.sh中的格式进行规范化等操作。
输入: 

sed -i 's/\r$//' start.sh

格式规范完成之后,我们就准备开始配置一些开机启动的程序文件了

二、编辑开机自启文件

2.1、创建rc-local.service文件

sudo vim /etc/systemd/system/rc-local.service

 将下面的代码段复制并粘贴至rc-local.service文件中

[Unit]
 Description=/etc/rc.local Compatibility
 ConditionPathExists=/etc/rc.local

[Service]
 Type=forking
 ExecStart=/etc/rc.local start
 TimeoutSec=0
 StandardOutput=tty
 RemainAfterExit=yes
 SysVStartPriority=99

[Install]
 WantedBy=multi-user.target
 Alias=rc-local.service

大致意思为

Type指定了我的类型是simple
after指定了启动network.service服务后开始启动我的服务,
ExecStart指定了执行/usr/bin/python3 server.py ,
WorkingDirectory指定了工作空间在
PrivateTmp指定了开启独立的进程空间

2.2、创建rc.local文件,设置开机启动的脚本

sudo vim /etc/rc.local

  编辑rc.local文件,将刚刚所编辑的start.sh文件所在路径放入即可

如:

#!/bin/bash
# rc.local
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
# In order to enable or disable this script just change the execution
# bits.
# By default this script does nothing.
# 可以在 exit 0 之前添加需要开机启动的程序
bash /xxx/xxx/xxx/start.sh &

exit 0

编辑完成后esc,再输入wq!即可保存

2.3、设置开机自启命令

sudo systemctl start rc-local.service                     启动服务
sudo systemctl enable rc-local.service                    开机自动启动
sudo systemctl daemon-reload                              更新服务
sudo systemctl restart rc-local.service                   重启服务
sudo systemctl status rc-local.service                    查看当前服务状态

2.3.1、输入sudo systemctl enable rc-local.service时出现错误

请务必认真检查之前的步骤是否已完成、或检查sh文件中代码编写是否有误

2.3.2后续显示如此状态即表示已成功完成开机自启 

Ubuntu 设置开机自启服务

三、常见错误

3.1、我们在编辑.sh文件的过程中可能会出现虚拟环境失败的问题

Ubuntu 设置开机自启服务

 在此,我们可以将.sh中切换环境的代码按顺序更改

source activate base;
source activate 要切换的虚拟环境名称

3.2、虚拟环境中python运行失败

当在虚拟环境中python运行失败时,我们可将其运行方式改成

/home/xxx/anaconda3/envs/xxxxxxxxxxx/bin/python xxx.py

四、结语

创作不易,能帮助大家及时闭坑,也是我的荣幸

若本篇文章能帮助你解决现所出现的问题,望请读者点赞加关注~

后续作者将会发布一篇新文章,为各位讲解本文中所使用的到的systemctl系统启动项,欢迎大家来捧场!

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
青葱年少的头像青葱年少普通用户
上一篇 2023年3月9日 下午11:32
下一篇 2023年3月9日 下午11:33

相关推荐