美文网首页Linux收藏
Ubuntu 设置开机脚本

Ubuntu 设置开机脚本

作者: 承诺一时的华丽 | 来源:发表于2022-03-12 11:11 被阅读0次

1. 编辑 rc-local.service 文件

sudo chmod 777 /lib/systemd/system/rc-local.service
sudo gedit /lib/systemd/system/rc-local.service
  • rc-local.service文件尾部添加以下内容:

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

  • 编辑后效果
#  SPDX-License-Identifier: LGPL-2.1+
#
#  This file is part of systemd.
#
#  systemd is free software; you can redistribute it and/or modify it
#  under the terms of the GNU Lesser General Public License as published by
#  the Free Software Foundation; either version 2.1 of the License, or
#  (at your option) any later version.

# This unit gets pulled automatically into multi-user.target by
# systemd-rc-local-generator if /etc/rc.local is executable.
[Unit]
Description=/etc/rc.local Compatibility
Documentation=man:systemd-rc-local-generator(8)
ConditionFileIsExecutable=/etc/rc.local
After=network.target

[Service]
Type=forking
ExecStart=/etc/rc.local start
TimeoutSec=0
RemainAfterExit=yes
GuessMainPID=no

# 在此处添加
[Install]
WantedBy=multi-user.target
Alias=rc-local.service

2、编辑 rc.local 文件

  • 编辑rc.local文件并添加要开机执行的脚本,第一行#!/bin/sh,尾行exit 0。( ubuntu18.04 版本之后默认没有/etc/rc.local文件,需要自己创建)
  • 添加下列内容:
sudo gedit /etc/rc.local
  • 内容
#!/bin/sh
echo "看到这行字,说明添加自启动脚本成功。" > /usr/local/test.log
# 中间这一段就是脚本的内容,例如:sudo ssr start
exit 0
  • 自定义启动相关脚本 , 通过su - xxxx执行指定不同用户权限的脚本
#!/bin/sh
echo "看到这行字,说明添加自启动脚本成功。" > /usr/local/test.log
su - xxxx -c "/home/xxxx/service/autostart.sh"
su - xxxx2 -c "/home/xxxx2/website/autostart.sh"
exit 0
  • 给 rc.local文件加上权限。
sudo chmod +x /etc/rc.local

3.、创建软链接

/etc/systemd/system/目录下创建软链接。创建软链接类似于windows下创建快捷方式。

4、创建方式:ln -s 原目录 映射目录

sudo ln -s /lib/systemd/system/rc-local.service /etc/systemd/system/ 

5、自定义用户脚本

gedit autostart.sh
  • 脚本内容
#!/bin/bash

# source  /home/xxxx/anaconda3/bin/activate # archlinux 激活方式一

source /home/xxxx/anaconda3/etc/profile.d/conda.sh # ubuntu 激活方式二
cd /home/xxxx/service
conda activate xxxx
nohup python main.py &

相关文章

网友评论

    本文标题:Ubuntu 设置开机脚本

    本文链接:https://www.haomeiwen.com/subject/oyukdrtx.html