Set windows boot script to modify the configuration file and restart the service

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/qq1124794084/article/details/83823577

Have a dynamic ip test machine, deploy Nginx above, and then restart the machine after each ip will always change, need to change the configuration file and restart nginx nginx.conf service.

Solution So to solve this problem, think of:

1, python script to solve modify the configuration and restart the service

2, the python script made into exe file

3, exe script added to the boot

A, python script

# -*- 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()

Second, the use pyinstaller made into exe file

python pyinstaller.py -F checkconf.py

Third, add the boot program

Remember to set the script to execute when the server starts, and is set to administrator privileges. Otherwise the C disk file can not be written

 

Restart test OK

Guess you like

Origin blog.csdn.net/qq1124794084/article/details/83823577