docs(step1): add wireguard server/client scripts + reset guide
This commit is contained in:
93
scripts/wireguard/wg_client.py
Executable file
93
scripts/wireguard/wg_client.py
Executable file
@@ -0,0 +1,93 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from datetime import datetime
|
||||
|
||||
WG_DIR = Path("/etc/wireguard")
|
||||
WG0 = WG_DIR / "wg0.conf"
|
||||
|
||||
|
||||
def require_root():
|
||||
if os.geteuid() != 0:
|
||||
print("ERROR: run as root (sudo).", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def run(cmd, check=True, capture=False):
|
||||
return subprocess.run(
|
||||
cmd,
|
||||
check=check,
|
||||
text=True,
|
||||
stdout=subprocess.PIPE if capture else None,
|
||||
stderr=subprocess.PIPE if capture else None,
|
||||
)
|
||||
|
||||
|
||||
def backup_if_exists(p: Path):
|
||||
if p.exists():
|
||||
ts = datetime.now().strftime("%Y-%m-%d_%H%M%S")
|
||||
b = p.with_name(p.name + f".bak.{ts}")
|
||||
shutil.copy2(p, b)
|
||||
|
||||
|
||||
def cmd_install(src: str):
|
||||
srcp = Path(src)
|
||||
if not srcp.exists():
|
||||
raise RuntimeError(f"Missing source config: {srcp}")
|
||||
WG_DIR.mkdir(parents=True, exist_ok=True)
|
||||
os.chmod(WG_DIR, 0o700)
|
||||
backup_if_exists(WG0)
|
||||
shutil.copy2(srcp, WG0)
|
||||
os.chmod(WG0, 0o600)
|
||||
os.chown(WG0, 0, 0)
|
||||
print(f"OK: installed {WG0}")
|
||||
|
||||
|
||||
def cmd_up():
|
||||
run(["wg-quick", "up", "wg0"], check=True)
|
||||
|
||||
|
||||
def cmd_down():
|
||||
run(["wg-quick", "down", "wg0"], check=False)
|
||||
|
||||
|
||||
def cmd_status():
|
||||
run(["wg", "show"], check=False)
|
||||
run(["ip", "a", "show", "wg0"], check=False)
|
||||
|
||||
|
||||
def main():
|
||||
require_root()
|
||||
p = argparse.ArgumentParser(prog="wg_client.py")
|
||||
sub = p.add_subparsers(dest="cmd", required=True)
|
||||
|
||||
i = sub.add_parser("install")
|
||||
i.add_argument("config", help="Path to clientX.conf from server export")
|
||||
|
||||
sub.add_parser("up")
|
||||
sub.add_parser("down")
|
||||
sub.add_parser("status")
|
||||
|
||||
args = p.parse_args()
|
||||
|
||||
try:
|
||||
if args.cmd == "install":
|
||||
cmd_install(args.config)
|
||||
elif args.cmd == "up":
|
||||
cmd_up()
|
||||
elif args.cmd == "down":
|
||||
cmd_down()
|
||||
elif args.cmd == "status":
|
||||
cmd_status()
|
||||
except Exception as e:
|
||||
print(f"ERROR: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
Reference in New Issue
Block a user