logo头像
Snippet 博客主题

linux上使用python自动重启服务器

一.环境安装

首先要电脑要有pip如果没有直接执行yum install pip安装即可

1
[root@localhost lzq]# yum install pip

安装schedule库

1
[root@localhost lzq]# pip install schedule

二.简单定时重启

这个非常简单

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import schedule
import time
import os

def job():
os.system('/home/work/tool/tomcat8.3.5/bin/shutdown.sh') #关闭服务器
time.sleep(20); #停顿20秒
os.system('/home/work/tool/tomcat8.3.5/bin/startup.sh') #启动服务


schedule.every().day.at("10:00").do(job) #每天10点执行job

while True:
schedule.run_pending()
time.sleep(1);
三.判断ip是否能ping来重启服务器

如果服务器和数据库的连接突然断开了,然后又连接上,不重启服务器就不能使用。

编写shell ping命令,命令返回0表示能够ping通,返回1表示不能够ping通。

1
2
[lzq@localhost ~]$ ping -c 3 192.168.1.100 | grep '0 received' | wc -l
1

这个判断服务器连接是否断开,断开后又连接上自动重启服务器的python代码也非常简单。

ping.sh文件的内容如下

1
2
PING=`ping -c 3 $1 | grep '0 received' | wc -l`
echo $PING

以下代码是在python3调试的,如果要升级python3参考python编译升级安装教程

ping.py文件的内容如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import subprocess
import time
import os
import sys
import datetime
from sys import stdout

def check_ping():
fileHandle = open (r'/home/lzq/公共/ping/ping.log', 'w', encoding='utf-8')
Status = True;
while True:
time.sleep(5)
p = subprocess.Popen(args=['./ping.sh 192.168.1.100'], stdout=subprocess.PIPE,shell = True)
result = p.stdout.read()
fileHandle.write(str(result)+"\n")
fileHandle.flush()
#print(result.strip())
if str(result.strip()) == str("b'1'"):
Status = False
#print("服务器连接错误")
fileHandle.write(str(Status)+"服务器连接错误,时间:"+datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+"\n")
fileHandle.flush()
else:
if not Status:
fileHandle.write("开始重启\n")
fileHandle.write("时间:"+datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+"\n")
restartserver()
fileHandle.write("重启完成\n")
fileHandle.flush()
Status = True

def restartserver():
os.system('/usr/local/home/tomcat-portal/bin/shutdown.sh')
time.sleep(20)
os.system('/usr/local/home/tomcat-portal/bin/startup.sh')

check_ping()
微信打赏