您的位置:首页 > 编程语言 > Python开发

Python 启动/停止脚本(后台服务)

2017-06-30 20:23 465 查看

简述

之前,用 Python/Tornado(Web 服务器框架)实现了一个 LDAP 相关的后台组件,用于客户端的用户认证。

若用命令行方式启动脚本,十分简单:

# python web_server.py


但为了方便部署,想要把它做成一个服务(service),这样就可以用服务来控制它的启动/停止,而且便于在开机时自启动。

简述

启动停止脚本

实现后台服务

版权所有:一去丶二三里,转载请注明出处:http://blog.csdn.net/liang19890820

启动/停止脚本

启动/停止脚本 - tornado-ldap(将来需要放置到
/etc/init.d/
中):

#!/bin/sh
# chkconfig: 123456 90 10
# LDAP server for user authentication
#
workdir=/etc/LDAP

daemon_start() {
cd $workdir
/usr/local/bin/python /etc/LDAP/web_server.py &
echo "Server started."
}

daemon_stop() {
pid=`ps -ef | grep '[p]ython /etc/LDAP/web_server.py' | awk '{ print $2 }'`
echo $pid
kill $pid
sleep 2
echo "Server killed."
}

case "$1" in
start)
daemon_start
;;
stop)
daemon_stop
;;
restart)
daemon_stop
daemon_start
;;
*)
echo "Usage: /etc/init.d/tornado-ldap {start|stop|restart}"
exit 1
esac
exit 0


第一行:
#!/bin/sh
是指此脚本使用
/bin/sh
来解释执行,
#!
是特殊的表示符,其后面根的是解释此脚本的 shell 的路径。

第二行:比较特殊,看起来像是注释,但
chkconfig
命令需要用到,必须存在。定义了在运行级别 1、2、3、4、5、6 中,服务将被激活(状态为:on),90 代表 Start 的顺序,10 代表 Kill(Stop)的顺序。

实现后台服务

要将其作为一个后台服务,大概分为以下几步:

1、为所需的服务创建一个用户

2、确保该用户对要设置的二进制文件具有完全访问权限:

/usr/bin/python


3、将启动/停止脚本
tornado-ldap
复制到
/etc/init.d/


4、确保脚本被标记为可执行文件:

chmod +x /etc/init.d/ldap


5、在运行级别 2、3、4、5 中启用配置:

chkconfig tornado-ldap on


6、启动/停止服务:

service tornado-ldap start  # 启动服务  也可使用:/etc/init.d/tornado-ldap start
service tornado-ldap stop  # 停止服务
service tornado-ldap restart  # 重启服务


当一切准备就绪,尝试启停服务:

[root@localhost ~]# service tornado-ldap stop  # 停止服务
1879
Server killed.
[root@localhost ~]# service tornado-ldap start  # 启动服务
Server started.
[root@localhost ~]# service tornado-ldap restart  # 重启服务
9885
Server killed.
Server started.


Ok,完美运行,而且当再次重启系统时,
tornado-ldap
服务也会自动启动。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息