Hi there! 👋 It looks like you mentioned sending two scripts, but I don’t see them attached. Could you share the scripts or clarify how I can assist? Whether it’s refining code, brainstorming ideas, or troubleshooting, I’m here to help! 🚀
Just paste them here, and I’ll craft actionable, well-structured solutions or feedback. Let’s dive in! 💻✨
User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
<#
.SYNOPSIS
Manages WireGuard tunnel service based on public IP changes.
Version 1.8: Added aggressive service cleanup (stop + force terminate) on tunnel failure.
Previous changes:
- Version 1.5: Added connectivity check to Test-TunnelUp; stops service if check fails. DAILY LOG ROTATION.
- Version 1.6: Fixed logic to preserve healthy tunnels when switching to Expected IP.
- Version 1.7: Added single retry logic for broken tunnels on Expected IP.
.DESCRIPTION
- Retrieves the current public IP.
- If IP matches ISP IP and tunnel isn't established, stops WireGuard service.
- If IP doesn't match ISP IP:
- If service runs but tunnel isn't up OR connectivity fails, stops service.
- If service is stopped, attempts to start it with retries.
- Failed attempts trigger a backoff period.
- LOGS ARE ROTATED DAILY (configurable): Log file overwritten after N hours.
- Logs are stored in the CURRENT USER'S "Documents\WireGuardLogs" folder (dynamic path).
- On tunnel failure, performs AGGRESSIVE CLEANUP (service stop + process termination if needed).
code
REQUIREMENTS:
- WireGuard installed as a Windows Service.
- Scheduled Task to run this script periodically (every 5-10 minutes recommended).
ExpectedPublicIP = "1.2.3.4" # <<< CHANGE: Your HOME/ISP public IP address (e.g., 203.0.113.42)
IPCheckURI = "https://icanhazip.com" # <<< CHANGE IF NEEDED: Service to fetch your current public IP (must return plain text IP)
$TunnelTestIP = "10.0.0.1" # <<< CHANGE: IP address ONLY reachable via WireGuard tunnel (server's WG IP)
***** 2. WIREGUARD SETTINGS *****
WireGuardTunnelName="wg−env:COMPUTERNAME" # <<< USUALLY FINE: Matches your WireGuard .conf file (without .conf extension)
# Example: if your file is wg-myhome.conf, set this to wg-myhome
***** 3. TIMEOUTS & RETRIES *****
TimeoutSeconds = 10 # <<< CHANGE IF SLOW NETWORK: Timeout for fetching public IP (seconds)
GetIPMaxRetries = 3 # <<< CHANGE IF UNSTABLE NETWORK: How many times to retry fetching public IP
GetIPRetryDelay = 5 # <<< CHANGE IF NEEDED: Delay between IP fetch retries (seconds)
TunnelStartRetries = 3 # <<< CHANGE IF WG IS FLAKY: How many times to retry starting WireGuard service
TunnelStartDelay = 15 # <<< ADJUST BASED ON WG INIT TIME: Seconds to wait for tunnel to come up after start
PingTimeoutSeconds = 5 # <<< FINE-TUNE FOR LATENCY: Timeout for pinging $TunnelTestIP (seconds)
***** 4. BACKOFF & LOGGING *****
TunnelBackoffHours = 1 # <<< CHANGE FOR AGGRESSIVE NETWORKS: Hours to "cool down" after repeated failures
LogRotationAgeHours = 24 # <<< ADJUST FOR LOG SIZE: Rotate (overwrite) log file after this many hours
# Set to 168 (7 days) if you prefer weekly rotation
***** 5. SERVICE CONTROL *****
ServiceStopWaitSeconds = 10 # <<< RARELY NEEDS CHANGE: Timeout waiting for WireGuard service to stop cleanly
ForceTerminateOnFailure = true # <<< SET TO false IF YOU PREFER GENTLE STOPS ONLY (no process killing)
# If $true, script will FORCE-KILL WireGuard process if service stop fails
Function Get-PublicIP {
attempt=0while(attempt -lt GetIPMaxRetries) {
try {
ip = (Invoke-RestMethod -Uri IPCheckURTimeoutSeconds).Trim()
if (') { return IPCheckURI" -Level WARN
}
catch {
Write-Log "IP fetch failed (attempt attempt + 1)): _.Exception.Message)" -Level WARN
}
GetIPRetryDelay
}
Write-Log "Public IP fetch failed after null
}
Function Get-WGService {
return Get-Service -Name $ServiceName -ErrorAction SilentlyContinue
}
Function Start-WGService {
try {
Write-Log "Starting WireGuard service..."
Start-Service -Name ServiceName−ErrorActionStopWrTunnelStartDelay seconds for tunnel to potentially come up..."
Start-Sleep -Seconds (false
}
}
Function Stop-WGService {
svc=Get−WGServiceif(−notsvc) {
Write-Log "WireGuard service not found for stopping." -Level WARN
return true
}
if (svc.Status -ne 'Running') {
Write-Log "WireGuard service is already not running (svc.Status))."
return $true
}
Allow Log on as batch job in Local Security Policy [1][7]
Network Access
Ensure standard user has permissions for:
Public IP check endpoint (icanhazip.com)
WireGuard tunnel endpoint
Workflow Without Admin Rights
Scenario
Success?
Reason
Service already running
✅
Can check status
IP matches expected
✅
No action needed
Tunnel needs restart
❌
Service control blocked
Backoff file exists
✅
Script exits early
Partial functionality possible, but critical tunnel recovery actions will fail without elevated privileges.
Recommended Approach
Admin-Configured Scheduled Task
Runs with SYSTEM privileges
Bypasses user permission issues [2][5]
Registry Hack (For Testing Only)
powershell
# Grant service control to Users group
reg add "HKLM\SYSTEM\CurrentControlSet\Services\WireGuardTunnel$wg-service" /v ObjectName /t REG_SZ /d "NT AUTHORITY\Authenticated Users" /f
Note: Security risk - use only in lab environments
Without admin assistance, the script can monitor tunnel status but cannot perform corrective actions. Full functionality requires initial admin configuration of permissions and task scheduling.
User
change log file location as you suggest
Assistant
To modify the WireGuard script's log file location for standard user compatibility, make these changes:
wgSvc=Get−WGServiceif(−notwgSvc) {
Write-Log "WireGuard service not installed for tunnel 'WireGuardTunnelName′."−LevelERRORexitEXIT_CONFIG_ERROR
}
Core logic
if (currentIP−eqExpectedPublicIP) {
Write-Log "Current IP matches ExpectedPublicIP. Checking tunnel state..."
if (wgSvc.Status -eq 'Running') {
if (Test-TunnelUp) {
# Tunnel healthy, leave it running
Write-Log "Tunnel is UP and HEALTHY despite being on Expected IP. Leaving service running."
exit EXIT_SUCCESS
} else {
# Tunnel broken, stop it...
Write-Log "Tunnel running but not healthy. Stopping service..." -Level WARN
if (-not (Stop-WGService)) {
if (ForceTerminateOnFailure) {
try {
wgProcess = Get-Process | Where-Object { _.ProcessName -like "*wireguard*" }
if (wgProcess) {
Write-Log "Terminating WireGuard process(es)..."
wgProcess | Stop-Process -Force -ErrorAction Stop
}
}
catch {
Write-Log "Process termination failed: ($_.Exception.Message)" -Level ERROR
}
} else {
Write-Log "Gentle stop failed. Not forcing termination (config)." -Level WARN
}
}
code
Start-Sleep -Seconds $TunnelStartDelay
Write-Log "Attempting to restart WireGuard service after cleanup..."
if (Start-WGService) {
Write-Log "Service restarted and tunnel HEALTHY."
exit $EXIT_SUCCESS
} else {
Write-Log "Restart failed. Entering backoff." -Level ERROR
Set-Backoff
exit $EXIT_SERVICE_ERROR
}
}
} else {
Write-Log "Service already stopped, expected on ISP IP."
}
exit $EXIT_SUCCESS
}
else {
# Not on Expected IP: Ensure tunnel is UP and WORKING
Write-Log "Current IP does NOT match ExpectedPublicIP. Ensuring tunnel is UP and WORKING..."
if (wgSvc.Status -eq 'Running') {
if (Test-TunnelUp) {
Write-Log "Service running and tunnel healthy. No action needed."
exit EXIT_SUCCESS
}
else {
Write-Log "Tunnel check FAILED while service is running. Forcing cleanup..." -Level WARN
if (-not (Stop-WGService)) {
if (ForceTerminateOnFailure) {
try {
wgProcess = Get-Process | Where-Object { _.ProcessName -like "*wireguard*" }
if (wgProcess) {
Write-Log "Terminating WireGuard process(es)..."
wgProcess | Stop-Process -Force -ErrorAction Stop
}
}
catch {
Write-Log "Process termination failed: ($_.Exception.Message)" -Level ERROR
}
}
}
code
Start-Sleep -Seconds $TunnelStartDelay
Write-Log "Restarting WireGuard service after cleanup..."
if (Start-WGService) {
Write-Log "Service restarted and tunnel HEALTHY."
exit $EXIT_SUCCESS
} else {
Write-Log "Restart failed. Entering backoff." -Level ERROR
Set-Backoff
exit $EXIT_SERVICE_ERROR
}
}
}
else {
# Service stopped, try starting with retries
Write-Log "Service is stopped. Attempting to start tunnel..."
$startedSuccessfully = $false
for ($try = 1; $try -le $TunnelStartRetries; $try++) {
Write-Log "Starting service (attempt $try/$TunnelStartRetries)..."
if (Start-WGService) {
Write-Log "Service started and tunnel is HEALTHY."
$startedSuccessfully = $true
break
}
else {
Write-Log "Tunnel did not come up successfully on attempt $try." -Level WARN
Stop-WGService
if ($try -lt $TunnelStartRetries) {
Write-Log "Retrying in $GetIPRetryDelay seconds..."
Start-Sleep -Seconds $GetIPRetryDelay
}
}
}
if (-not $startedSuccessfully) {
Write-Log "Failed to establish a working tunnel after $TunnelStartRetries attempts." -Level ERROR
Set-Backoff
exit $EXIT_SERVICE_ERROR
}
}
Service PID Tracking
Replace broad process killing with service-specific PID termination (see Critical Fixes).
Edge Case Handling
Check for stale backoff files (e.g., from system time changes).
Handle WireGuardTunnelName mismatches (e.g., log all tunnel interfaces if the expected one is missing).
📋 Deployment Checklist
Scheduled Task Setup
Run as the logged-in user (not SYSTEM) to ensure log/backoff file access.
Trigger every 5-10 minutes.
Enable "Run with highest privileges".
Testing
Simulate IP changes (e.g., disconnect VPN) to verify tunnel shutdown.
Block $TunnelTestIP temporarily to test connectivity checks.
Log Monitoring
Check wg_ip_check.log for ERROR entries after deployment.
Confirm log rotation works by setting $LogRotationAgeHours = 1 during testing.
🔄 Example Workflow
IP Change Detected
Script stops WireGuard if on home IP.
Starts service + verifies tunnel when on external IP.
Tunnel Failure
Aggressive cleanup (service stop + process kill).
Backoff file created to prevent rapid retries.
Recovery
After $TunnelBackoffHours, the script resumes normal operation.
This script is well-structured for production use! With minor tweaks to process handling and deployment setup, it’ll reliably manage WireGuard tunnels. Let me know if you need help implementing these changes! 🚀