前言
在项目中,用Frp进行了内网穿透,但是由于网络存在波动的可能,而这样也可能会导致Frp中断,所以就想着通过定时重启frp程序来规避这种情况,如下:
一、依赖项安装
这里所需要的python依赖项相对较少,只需要安装下schedule即可(这个包很小,无需镜像也会很快装完),这个是定时任务时会用到的,直接在运行的python环境下执行以下命令:
pip install schedule
二、重启任务
这一部分我们将贴出代码,大致逻辑是先检测到我们要重启的程序id,然后kill掉之后,进行重新启动,代码如下:
import os,sys,schedule
import subprocess,time
def restart_frp():
child =subprocess.Popen(["pgrep","-f","xxx"],stdout=subprocess.PIPE,)
pid=child.stdout.read().decode("utf-8").strip()
#print(pid)
if pid!="":
os.system("kill -9 "+pid)
child2=subprocess.Popen("xxx",stdout=subprocess.PIPE,shell=True)
print(time.strftime("%Y-%m-%d %H:%M",time.localtime()))
if __name__ == '__main__':
restart_frp()
schedule.every().hour.do(restart_frp)
while True:
schedule.run_pending()
其中的xxx均为你要操作的程序名称
三、bug记录
自己在运行中若遇到如下错误:
则执行如下操作:
第一步,执行命令
ls -l /bin/sh
若显示结果为:/bin/sh -> dash,那就执行第二步:
sudo dpkg-reconfigure dash (出现窗口选择no)
第三步,再次执行命令:
ls -l /bin/sh
显示为 /bin/sh -> bash后,重新运行程序即可
参考链接:bug解决
总结
以上就是这篇文章的全部内容,如有不对,还望指正。