版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq1124794084/article/details/83823577
有一台动态ip的测试机器,上面部署Nginx,然后每次重启机器后ip总会变动,需要改nginx.conf配置文件和重启nginx服务。
所以要解决这个问题,想到的解决方法:
1、python脚本来解决修改配置和重启服务
2、把python脚本制作成exe文件
3、exe脚本添加为开机启动
一、python脚本
# -*- coding:UTF-8 -*-
import re
import os
def checkconf():
r = os.popen("ipconfig /all")
text = r.read()
r.close()
result = text
pat = "(\d+\.\d+\.\d+\.\d+)"
myaddr = re.findall(pat, result)[0]
print myaddr
#匹配ip地址
pattern = re.compile(r'\d+\.\d+\.\d+\.\d+')
#设置flag判断是否需要改文件和重启
flag = False
#替换nginx.conf中的ip为靶机服务器ip地址
#将文件读取到内存中
with open("C:\Program Files\\nginx\\conf\\nginx.conf","r") as f:
lines = f.readlines()
for line in lines:
result = pattern.findall(line)
if len(result) > 0:
if (result[0]) == myaddr:
flag = True
break
if flag == True:
#写的方式打开文件
with open("C:\Program Files\\nginx\\conf\\nginx.conf","w") as f_w:
for line in lines:
result = pattern.findall(line)
if len(result) > 0:
print result
#替换
line = line.replace(result[0],myaddr)
f_w.write(line)
#替换ip地址后重启nginx服务
#os.system('C:\Program Files\\nginx\\nginx-service.exe restart')
r = os.popen("nginx-service.exe restart")
text = r.read()
r.close()
print text
else:
pass
if __name__ == '__mian__':
checkconf()
二、使用pyinstaller制作成exe文件
python pyinstaller.py -F checkconf.py
三、添加为开机计划
记得设置为服务器启动时执行脚本,并且设置为管理员权限。否则C盘文件无法写入
重启测试OK