add rotate
This commit is contained in:
		
							
								
								
									
										49
									
								
								scripts/rotate.py
									
									
									
									
									
										Executable file
									
								
							
							
						
						
									
										49
									
								
								scripts/rotate.py
									
									
									
									
									
										Executable file
									
								
							@@ -0,0 +1,49 @@
 | 
			
		||||
#!/usr/bin/env python3
 | 
			
		||||
import configparser
 | 
			
		||||
import subprocess
 | 
			
		||||
import re
 | 
			
		||||
import io
 | 
			
		||||
 | 
			
		||||
def offline():
 | 
			
		||||
    expr = re.compile("ips:[^()]+handshake")
 | 
			
		||||
    proc = subprocess.run(["wg", "show", "vpn"], capture_output=True, encoding="utf-8")
 | 
			
		||||
    return len(expr.findall(proc.stdout)) == 0
 | 
			
		||||
 | 
			
		||||
def rotate_conf():
 | 
			
		||||
    iface = None
 | 
			
		||||
    peers = []
 | 
			
		||||
    try:
 | 
			
		||||
        with open("/snacks/wireguard/wg.conf", "r") as f:
 | 
			
		||||
            pattern = re.compile("\[[^\[\]]+\][^\[\]]+")
 | 
			
		||||
            sections = []
 | 
			
		||||
            for section in re.findall(pattern, f.read()):
 | 
			
		||||
                sections.append(section.strip())
 | 
			
		||||
    except Exception as e:
 | 
			
		||||
        print(e)
 | 
			
		||||
    else:
 | 
			
		||||
        for section in sections:
 | 
			
		||||
            config = configparser.ConfigParser()
 | 
			
		||||
            config.read_string(section)
 | 
			
		||||
            if "Peer" in config.sections():
 | 
			
		||||
                peers.append(config)
 | 
			
		||||
            else:
 | 
			
		||||
                iface = config
 | 
			
		||||
    buf = io.StringIO()
 | 
			
		||||
    try:
 | 
			
		||||
        iface.write(buf)
 | 
			
		||||
    except Exception as e:
 | 
			
		||||
        print(e)
 | 
			
		||||
    else:
 | 
			
		||||
        first = peers.pop(0)
 | 
			
		||||
        peers.append(first)
 | 
			
		||||
        for peer in peers:
 | 
			
		||||
            peer.write(buf)
 | 
			
		||||
        try:
 | 
			
		||||
            with open("/snacks/wireguard/wg.conf", "w") as f:
 | 
			
		||||
                f.write(buf.getvalue())
 | 
			
		||||
        except Exception as e:
 | 
			
		||||
            print(e)
 | 
			
		||||
 | 
			
		||||
if offline():
 | 
			
		||||
    rotate_conf()
 | 
			
		||||
    subprocess.run(["systemctl", "restart", "vpnclient-wg"])
 | 
			
		||||
		Reference in New Issue
	
	Block a user