Linux环境下给python项目写个启停服务

写个服务,写完后放在/lib/systemd/system路径下
update_rule.server

[Unit]
Description = TinyScan update rule

[Service]
Type=forking
WorkingDirectory=/root/TinyScan_Auto_Deploy/init_cve
ExecStart=/root/TinyScan_Auto_Deploy/init_cve/start.sh start
ExecStop=/root/TinyScan_Auto_Deploy/init_cve/start.sh stop
ExecReload=/root/TinyScan_Auto_Deploy/init_cve/start.sh restart
Restart=always

[Install]
WantedBy=multi-user.target

start.sh

#!/bin/bash

SERVICE_NAME="update-rule"
#CONFIG_NETCARD_NAME=`cat /tinyscan/config/config.ini | grep -zo '\[config_net_card\]\sname=.*' | sed -n '2p' | awk -F '=' '{print $2}'`
#SERVER_NETCARD_NAME=`cat /tinyscan/config/config.ini | grep -zo '\[net_card\]\sname=.*' | sed -n '2p' | awk -F '=' '{print $2}'`

pid=`ps -ef | grep 'python3 /root/TinyScan_Auto_Deploy/init_cve/update_rule.py' | grep -v 'grep' | awk '{print $2}'`

up()
{
#  if [ ${CONFIG_NETCARD_NAME} != ${SERVER_NETCARD_NAME} ]; then
 #   iptables -A INPUT -i ${SERVER_NETCARD_NAME} -p tcp --dport 1080 -j DROP
 # fi
 # source /tinyscan/config/venv/bin/activate
  python3 /root/TinyScan_Auto_Deploy/init_cve/update_rule.py &
}

down()
{
  #if [ ${CONFIG_NETCARD_NAME} != ${SERVER_NETCARD_NAME} ]; then
  #  iptable -D INPUT -i ${SERVER_NETCARD_NAME} -p tcp --dport 1080 -j DROP
  #fi
  kill ${pid}
}

if [ ! $1 ]; then
  echo "Please specify args 'start|restart|stop'"
  exit
fi

if [ $1 == 'start' ]; then
  if [ ! $pid ]; then
    up
  else
    echo "${SERVICE_NAME} is running! pid=$pid"
  fi
fi

if [ $1 == 'restart' ]; then
  if [ $pid ]; then
    down
  else
    sleep 3
    up
  fi
fi

if [ $1 == 'stop' ]; then
  if [ $pid ]; then
    down
  else
    echo "${SERVICE_NAME} is stopped"
  fi
fi

update_rule.py是一个定时任务

import os

import schedule
import time
import datetime

def job1():
    os.system('/root/TinyScan_Auto_Deploy/init_cve/sSnvd -u')





if __name__ == '__main__':
    # schedule.every(10).seconds.do(job1)
    schedule.every().day.at('11:00').do(job1)
    while True:
        schedule.run_pending()
        

当然单纯的定时任务可以利用crontab来搞定

crontab定时任务

cat /etc/crontab
crontab -e : 编辑定时任务(用户可以省略,默认是当前用户)
crontab -l : 查看定时任务(只查看当前用户的定时任务)
cat /var/log/cron : 可以查看到执行那些定时任务
cat /var/log/messages: 记录系统操作的日志,(例如:用户登录)

posted @ 2022-09-30 11:59  kopok  阅读(117)  评论(0编辑  收藏  举报