Ubuntu下设置开机后自动运行命令

从道理上来讲,Ubuntu开机应该是能够设置执行一些脚本的,事实上确实如此,网上给出了很多解决的方案,基本上是分为两种,

第一种是编辑/etc/下的rc.local脚本,

然后把对应的需要执行的脚本写在exit 0前面,在ubuntu16.06上亲测无效

第二种则是编辑一个shell脚本,然后在shell脚本中写入自己开机之后需要执行的命令,然后把该脚本拷贝进/etc/init.d/文件夹下,赋予可执行的权限,然后一行命令sudo update-rc.d 你的脚本 defaults 90

比如我这里先写一个开机自动挂载两个盘以及frpc内网穿透的服务,

然后命名为mount_and_frpc.sh,从桌面拷贝到文件夹/etc/init.d/下:sudo cp ./mount_and_frpc.sh /etc/init.d/,并且赋予可执行权限sudo chmod 775 ./mount_and_frpc.sh

然后执行该命令:sudo update-rc.d mount_and_frpc.sh defaults 90,然后会报如下错误:missing LSB tags and overrides,这参考下面这俩个链接

http://blog.bbzhh.com/index.php/archives/134.html, http://www.linuxdiyf.com/linux/26896.html

个时候需要在执行的命令前面加上这样一段话:

 

### BEGIN INIT INFO
# Provides:          svnd.sh
# Required-start:    $local_fs $remote_fs $network $syslog
# Required-Stop:     $local_fs $remote_fs $network $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: starts the svnd.sh daemon
# Description:       starts svnd.sh using start-stop-daemon
### END INIT INFO

 

然后执行:sudo update-rc.d mount_and_frpc.sh defaults 90,重启reboot即可

同样的,如果想取消该开机自启项,需要执行如下命令

cd /etc/init.d

sudo update-rc.d -f mount_and_frpc.sh remove

更多Ubuntu相关信息见Ubuntu 专题页面 http://www.linuxidc.com/topicnews.aspx?tid=2

本文永久更新链接地址http://www.linuxidc.com/Linux/2017-09/147178.htm

 

 

 

1.复制或软连接脚本到/etc/init.d/目录下
 
2.将脚本添加到初始化执行的队列中去
注意如果脚本需要用到网络,则NN需设置一个比较大的数字,如99。
命令:update-rc.d xxx defaults NN命令 #(NN为启动顺序)
ubuntu 16.04中一定要加上以下LSB信息,不然放入启动脚本的时候会报错无法开机启动。
#!/bin/sh
### BEGIN INIT INFO
# Provides:          svnd.sh
# Required-start:    $local_fs $remote_fs $network $syslog
# Required-Stop:     $local_fs $remote_fs $network $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: starts the svnd.sh daemon
# Description:       starts svnd.sh using start-stop-daemon
### END INIT INFO
 
3.设置脚本文件的权限
$ sudo chmod 755 /etc/init.d/svnd.sh (注意一定要设置权限,不然开机不会启动)
 
4.执行如下命令将脚本放到启动脚本中去:
$ cd /etc/init.d
$ sudo update-rc.d svnd.sh defaults 95
注:其中数字95是脚本启动的顺序号,按照自己的需要相应修改即可。在你有多个启动脚本,而它们之间又有先后启动的依赖关系时你就知道这个数字的具体作用了。
 
5.卸载启动脚本的方法:
$ cd /etc/init.d
$ sudo update-rc.d -f svnd.sh remove
 
posted @ 2018-11-25 08:36  weizhxa  阅读(11259)  评论(0编辑  收藏  举报