今天想给系统配置开机启动脚本,目的能够使用脚本实现开机自动启动synergy,梯子等程序。爬了诸多博客,基本是直接在/etc/rc.loca 里面写入执行的shell命令,但是这样无法成功。原因就是:ubuntu-16.10 开始不再使用initd管理系统,改用systemd。
systemd is now used for user sessions. System sessions had already been provided by systemd in previous Ubuntu releases.
解决办法:
step 1
cd /lib/systemd/system
sudo vim rc-local.service
使用vim编辑器打开rc-local.sevice这个文件后,看到的内容如下:
1 # SPDX-License-Identifier: LGPL-2.1+
2 #
3 # This file is part of systemd.
4 #
5 # systemd is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU Lesser General Public License as published by
7 # the Free Software Foundation; either version 2.1 of the License, or
8 # (at your option) any later version.
9
10 # This unit gets pulled automatically into multi-user.target by
11 # systemd-rc-local-generator if /etc/rc.local is executable.
12 [Unit]
13 Description=/etc/rc.local Compatibility
14 Documentation=man:systemd-rc-local-generator(8)
15 ConditionFileIsExecutable=/etc/rc.local
16 After=network.target
17
18 [Service]
19 Type=forking
20 ExecStart=/etc/rc.local start
21 TimeoutSec=0
22 RemainAfterExit=yes
23 GuessMainPID=no
step 2
我们需要在文件的下方进行添加一个Install段的代码,这部分的作用就是定义开机启动后执行的动作,内容为:
[Install]
WantedBy=multi-user.target
Alias=rc-local.service
step 3
编辑系统的/etc/rc.local 文件,这里你要写入的内容就是希望开机执行的命令,比如我希望开机自动启动trojan:
cd /usr/bin/trojan && sudo ./trojan &
# /usr/bin/下面的trojan是我自己创建文件夹,存放着trojan及其配置文件
如果没有/etc/rc.local文件,则自行创建一个即可:
touch /etc/rc.local
注意rc.loca的文件中的必须内容,我把系统中默认的格式复制过来,以期日后所需。
#!/bin/sh -e
#
# 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 chagne the execution
# bits.
#
# By default this script does nothing.
# to start the sslocal service when PC is open
# /home/vincent/.local/bin/sslocal -c /etc/shadowsocks.json &
cd /usr/bin/trojan && sudo ./trojan &
exit 0
step 4
改变这个文件的权限,让它可以被执行
sudo chmod +x /etc/rc.local
step 5
在/lib/systemd/system路径下,创建一个软链接。
多啰嗦两句:systemd默认读取/etc/systemd/system/下的配置文件,而该目录下的文件会链接/lib/systemd/system/下面的文件。ubuntu 18.04 安装完后/lib/systemd/system/就会有rc-local.service,这个是我们刚刚编辑过的文本。创建这个软链接是为了让系统启动时通过/etc/systemd/system/读取到rc.loca.service。
ln -s /lib/systemd/system/rc.local.service /etc/systemd/system/
按照以上步骤,即可实现开机启动希望的应用了。