执行命令:编辑"/etc/rc.local",添加你想开机运行的命令
运行程序脚本:之后在文件最后一行添加要执行程序的全路径。
比如,每次开机时要执行一个hello.sh,这个脚本置于/usr下边,那就可以在"/etc/rc.local"中加一行"/usr/./hello.sh"深度linux系统,或则"cd/opt&&./hello.sh"
注意,你的命令应当添加在:exit0之前
在/etc/init.d目录下添加自启动脚本
linux在“/etc/rc.d/init.d”下有好多的文件,每位文件都是可以听到内容的,虽然都是一些shell脚本或则可执行二补码文件Linux开机的时侯,会加载运行/etc/init.d目录下的程序,因而我们可以把想要手动运行的脚本放在这个目录下即可。系统服务的启动就是通过这些方法实现的。
运行级别设置
简单的说,运行级就是操作系统当前正在运行的功能级别。
不同的运行级定义如下:
# 0 - 停机(千万不能把initdefault 设置为0 )
# 1 - 单用户模式 进入方法#init s = init 1
# 2 - 多用户,没有 NFS
# 3 - 完全多用户模式(标准的运行级)
# 4 - 没有用到
# 5 - X11 多用户图形模式(xwindow)
# 6 - 重新启动 (千万不要把initdefault 设置为6 )
例:在Ubuntu/debain里,可以使用update-rc.d命令来把示例脚本:/etc/init.d/proxy安装到各个runlevel中。
update-rc.d proxy defaults 99
复制
update-rc.d前面有三个参数,分别是/etc/init.d下的脚本名子,默认安装方法,运行的优先级。优先级的数字越大linux数据恢复,表示越迟运行linux设置开机启动,这儿我们把自己写的服务放到最后运行。
假如要卸载随机启动的服务,执行
update-rc.d -f proxy remove
复制
在update-rc.d安装的时侯提示了警告信息,是由于我们写的/etc/init.d/proxy太狭小了linux设置开机启动,只包含了我们想要的命令,连LSB的信息也没有提供。
update-rc.d: warning: /etc/init.d/proxy missing LSB information
update-rc.d: see
复制
只须要对自启动脚本做一些小改动,就可以防止那种警告了。如下:
#!/bin/sh
### BEGIN INIT INFO
# Provides: proxy
# Required-Start: $remote_fs
# Required-Stop: $remote_fs
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start or stop the HTTP Proxy.
### END INIT INFO
case "$1" in
start)
start-stop-daemon --start --background --exec /root/proxy.py
;;
stop)
start-stop-daemon --stop --name proxy.py
esac
复制
到此,一个最简单的随机启动服务写好了,看上去文章挺长的,但显然也就几个命令而已。在上次开机启动的时侯,proxy.py都会以root用户身分被手动运行。
把脚本注册为系统服务
在/etc/init.d下新建示例脚本文件(startTest.sh),该脚本会启动/opt/test.sh。内容如下:
. /etc/init.d/functions
start() {
echo "Starting my process "
cd /opt
./test.sh
}
stop() {
killall test.sh
echo "Stoped"
}
复制
写了脚本文件然后事情还没有完,继续完成以下几个步骤:
chmod +x startTest #增加执行权限
chkconfig --add startTest #把startTest添加到系统服务列表
chkconfig startTest on #设定startTest的开关(on/off)
chkconfig --list startTest.sh #就可以看到已经注册了startTest的服务
复制