1、开机自动运行

假如Python自启动脚本为auto.py。那么用root权限编辑以下文件:

[root@docker-01 ~]# vim /etc/rc.local 
 #!/bin/bash
 # THIS FILE IS ADDED FOR COMPATIBILITY PURPOSES
 #
 # It is highly advisable to create own systemd services or udev rules
 # to run scripts during boot instead of using this file.
 #
 # In contrast to previous versions due to parallel execution during boot
 # this script will NOT be run after all other services.
 #
 # Please note that you must run 'chmod +x /etc/rc.d/rc.local' to ensure
 # that this script will be executed during boot.
 
 touch/var/lock/subsys/local
 /usr/bin/python3 /home/selfcs/auto.py > /home/selfcs/auto.log

linux python 开机自启动 linux开机自启动python脚本_linux python 开机自启动

2、让脚本定时启动

用root权限编辑以下文件

[root@docker-01 ~]# vim /etc/crontab
 ##创建定时任务
 [root@docker-01 ~]# crontab -e -u root ##-e修改 -u指定用户
 */10 * * * * /usr/sbin/ntpdate 0.cn.pool.ntp.org && hwclock --systohc>/dev/null 2>&1

linux python 开机自启动 linux开机自启动python脚本_docker_02

3、& 后台运行

将sh test.sh任务放到后台 ,关闭xshell,对应的任务也跟着停止。

[root@docker-01 ~]# sh test.sh &
 [1] 17717

4、nohup不挂断的运行

用nohup运行命令可以使命令永久的执行下去,和用户终端没有关系,例如我们断开SSH连接都不会影响他的运行,注意了nohup没有后台运行的意思;&才是后台运行,通常nuhup和&在一起执行。

[root@docker-01 ~]# nohup command > myout.file 2>&1 & ##本例子中,0 – stdin (standard input),1 – stdout (standard output),2 – stderr (standard error) ;
 2>&1是将标准错误(2)重定向到标准输出(&1),标准输出(&1)再被重定向输入到myout.file文件中。

5、创建一个配置文件

创建一个start.sh启动文件和stop.sh停止文件,把需要执行的命令放到脚本里面。

[root@localhost bin]# cat start.sh 
 /usr/local/bin/mitmdump -p8888-s/home/smgadmin/web_crawler/scripts/dyscripty/bin/dyscripty.py >/dev/null 2>&1 &  ##启动文件
 [root@localhost bin]# sh start.sh 
 [root@localhost bin]# cat stop.sh 
 kill-9 `ps auxwww | grep 'mitmdump' | grep '/home/smgadmin/web_crawler/scripts/dyscripty/bin/dyscripty.py' | grep -v grep | awk '{print $2}'` ##停止文件
 [root@localhost bin]# sh stop.sh