【原创】OpenConnect** python实现ping自启进程守护
本帖最后由 rainsun 于 2017-3-17 17:27 编辑在OpenWRT路由上搭了个openConnect**方便远程回家进行各种管理
用的是Cisco AnyConnect Secure Mobility Client的 客户端,这个客户端不能记住密码,而且断线后不能重连
本文最要是用python脚本 socket实现,循环检测路由器状态,如果链路不通则重新启动**
脚本如下,或下载附件,
#!/usr/bin/python
#coding=utf-8
import os
import socket
import subprocess
import time
#Windows
p_name = "**cli.exe"
p_path = "C:\\Program Files\\Cisco\\Cisco AnyConnect Secure Mobility Client\\auto**64\\connect.bat"
d_path = "C:\\Program Files\\Cisco\\Cisco AnyConnect Secure Mobility Client\\auto**64\\disconnect.bat"
#Linux平台调用ps命令/Win平台调用tasklist命令,判断进程是否存在,传入进程名称,返回为查询得到的进程个数
def process_exit(process_name):
#Linux
#p_checkresp = os.popen('ps aux | grep "' + process_name + '" | grep -v grep').readlines()
#Windows,为避免进程名称被截断,输出格式为csv,使用tasklist /fo csv
p_checkresp = os.popen('tasklist /fo csv | find "' + process_name + '"').readlines()
return len(p_checkresp)
def process_exec(process_path):
#将工作目录切换到启动脚本所在目录,解决部分进程启动时依赖工作目录问题
os.chdir(os.path.dirname(process_path))
#Linxu
#os.system(process_path)
#Windows
os.startfile(process_path)
#可用于检测程序是否正常,如检测80端口是否正常
def check_aliveness(ip, port):
sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sk.settimeout(1)
try:
sk.connect((ip,port))
#print 'server %s %d service is OK!' %(ip,port)
return True
except Exception:
#print 'server %s %d service is NOT OK!'%(ip,port)
return False
finally:
sk.close()
return False
#for var in range(1,10): #该条件执行10次
var = 1
while var == 1: #该条无限循环,CTRL+C中断
time.sleep(2)
if check_aliveness('192.168.1.12', 80) == False:
print "The network is disconnected and reconnected!"
#执行启动命令
process_exec(p_path)
time.sleep(300)
#等待180秒后,查询进程个数大于1,返回1,启动失败
if process_exit(p_name) >= 1:
print "Startup failed!"
process_exec(p_path)
elif check_aliveness('192.168.1.12', 80) == True:
print "Start a successful, smooth network!"
else:
print "Startup failed!"
process_exec(p_path)
else:
print 'The network is open!'
技术男{:1_245:}
页:
[1]