i will send 2 part of script due to character limitations
- User
i will send 2 part of script due to character limitations
Assistant
Okay, I understand. I'm ready for the first part of your script. I will wait for you to send it.
- User
<# .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).
REQUIREMENTS: - WireGuard installed as a Windows Service. - Scheduled Task to run this script periodically (every 5-10 minutes recommended).#>
=======================================================================================
--- ADJUSTABLE CONFIGURATION PARAMETERS (CHANGE THESE AS NEEDED) ---------------------
=======================================================================================
***** 1. NETWORK SETTINGS *****
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 *****
env:COMPUTERNAME" # <<< USUALLY FINE: Matches your WireGuard .conf file (without .conf extension) # Example: if your file is
wg-myhome.conf, set this towg-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
=======================================================================================
--- INTERNAL CONSTANTS (DON'T TOUCH UNLESS YOU KNOW WHAT YOU'RE DOING) ---------------
=======================================================================================
$ServiceName = "WireGuardTunnel`$$WireGuardTunnelName" # Derived service name (matches WG installation)
=======================================================================================
--- DYNAMIC LOG PATHS (AUTO-DETECTED, NO NEED TO CHANGE) ----------------------------
=======================================================================================
These resolve to the CURRENT USER'S "Documents\WireGuardLogs" folder, even if redirected
LogDir = Join-Path -Path LogFile = Join-Path -Path BackoffFile = Join-Path -Path $LogDir -ChildPath "wg_backoff.tmp"
Ensure log directory exists (done ONCE at startup)
if (-not (Test-Path LogDir)) { New-Item -ItemType Directory -Path LogDir -Force | Out-Null Write-Host "Created log directory: $LogDir" -ForegroundColor Cyan }
--- Exit Codes (for task schedulers, monitoring tools) ---
EXIT_CONFIG_ERROR = 1 EXIT_SERVICE_ERROR = 3
#region --- Helper Functions --- Function Write-Log { Param( [string]Level = "INFO" ) logLine = "Level - $Message"
# Daily log rotation check if (Test-Path $LogFile) { $logAge = (Get-Date) - (Get-Item $LogFile).LastWriteTime if ($logAge.TotalHours -ge $LogRotationAgeHours) { Write-Host "Log file older than $LogRotationAgeHours hours. Rotating (overwriting)..." -ForegroundColor Yellow try { [System.IO.File]::WriteAllText($LogFile, "") # Clear file } catch { Write-Host "Failed to rotate log file: $($_.Exception.Message)" -ForegroundColor Red } } } switch ($Level) { "INFO" { Write-Host $logLine -ForegroundColor Cyan } "WARN" { Write-Host $logLine -ForegroundColor Yellow } "ERROR" { Write-Host $logLine -ForegroundColor Red } } try { [System.IO.File]::AppendAllText($LogFile, "$logLine`r`n") } catch { Write-Host "Log write failed: $($_.Exception.Message)" -ForegroundColor Red }}
Function Get-PublicIP { attempt -lt GetIPMaxRetries) { try { ip = (Invoke-RestMethod -Uri TimeoutSeconds).Trim() if (') { return ip } Write-Log "Invalid IP format from 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 TunnelStartDelay seconds for tunnel to potentially come up..." Start-Sleep -Seconds TunnelStartDelay return (Test-TunnelUp) } catch { Write-Log "Failed to start service: (false } }
Function Stop-WGService { svc) { 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 }
try { Write-Log "Stopping WireGuard service..." Stop-Service -Name $svc.Name -Force -ErrorAction Stop $svc.WaitForStatus('Stopped', (New-TimeSpan -Seconds $ServiceStopWaitSeconds)) Write-Log "Service stopped." return $true } catch { Write-Log "Service stop failed: $($_.Exception.Message)" -Level ERROR return $false }}
Function Test-TunnelUp { iface = Get-NetAdapter | Where-Object { _.InterfaceDescription -like "WireGuard Tunnel*" -and WireGuardTunnelName*"} if (-not iface) { Write-Log "Tunnel interface 'WireGuardTunnelName' not found." -Level WARN return $false }
if ($iface.Status -ne "Up") { Write-Log "Tunnel interface '$($iface.Name)' found but is DOWN." -Level WARN return $false } Write-Log "Tunnel interface '$($iface.Name)' is UP. Testing connectivity..." if (-not $TunnelTestIP) { Write-Log "No TunnelTestIP configured. Assuming tunnel is up if interface is up." -Level WARN return $true } Write-Log "Pinging $TunnelTestIP via tunnel..." $timeoutMs = $PingTimeoutSeconds * 1000 ping.exe -n 1 -w $timeoutMs $TunnelTestIP | Out-Null if ($LASTEXITCODE -eq 0) { Write-Log "Tunnel connectivity VERIFIED to $TunnelTestIP." return $true } else { Write-Log "Tunnel connectivity FAILED. Could not ping $TunnelTestIP (timeout: $($PingTimeoutSeconds)s). ping.exe Exit Code: $LASTEXITCODE" -Level WARN return $false }}
Function Set-Backoff { try { Remove-Item BackoffFile -Encoding UTF8 Write-Log "Backoff set for TunnelBackoffHours hour(s)." } catch { Write-Log "Error writing backoff file: ($_.Exception.Message)" -Level ERROR } }
Function Test-BackoffActive { if (-not (Test-Path BackoffFile)) { return false } try { BackoffFile) lastTry if (TunnelBackoffHours) { TunnelBackoffHours - (true } Remove-Item BackoffFile -ErrorAction SilentlyContinue } catch { Write-Log "Invalid backoff file. Resetting." -Level WARN Remove-Item BackoffFile -ErrorAction SilentlyContinue } return $false } #endregion
Assistant
Okay, I have received the first part of your PowerShell script. I'm ready for the second part whenever you are. I will combine them and then analyze the complete script to answer any questions you may have.
- User
=======================================================================================
--- Main Logic ------------------------------------------------------------------------
=======================================================================================
Write-Log "Script started"
Quick config validation
if (-not WireGuardTunnelName) { Write-Log "Missing ExpectedPublicIP or WireGuardTunnelName." -Level ERROR exit EXIT_CONFIG_ERROR } if (-not TunnelTestIP) { Write-Log "TunnelTestIP is not configured. Connectivity checks will be skipped." -Level WARN } elseif (') { Write-Log "Invalid TunnelTestIP format: EXIT_CONFIG_ERROR } if (IPCheckURI -notmatch '^https?://') { Write-Log "Invalid IPCheckURI: must start with http:// or https://" -Level ERROR exit EXIT_CONFIG_ERROR }
Backoff check (early exit)
if (Test-BackoffActive) { Write-Log "Exiting due to active backoff." exit $EXIT_SUCCESS }
Fetch current public IP
currentIP) { Write-Log "Public IP fetch failed after $GetIPMaxRetries attempts. Checking WireGuard status..." -Level ERROR
# Get WireGuard service status $wgSvc = Get-WGService if ($wgSvc -and $wgSvc.Status -eq 'Running') { Write-Log "WireGuard is running but network state is unknown. Stopping service..." -Level WARN if (-not (Stop-WGService)) { if ($ForceTerminateOnFailure) { try { $wgProcess = Get-Process | Where-Object { $_.ProcessName -like "*wireguard*" } if ($wgProcess) { Write-Log "Force-killing 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 } } } else { Write-Log "WireGuard is already stopped." } exit $EXIT_NETWORK_ERROR} Write-Log "Expected IP: currentIP"
Get WireGuard service handle
wgSvc) { Write-Log "WireGuard service not installed for tunnel 'EXIT_CONFIG_ERROR }
Core logic
if (ExpectedPublicIP) { 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 } }
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 } } }
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 } }}
Write-Log "Script finished successfully." exit $EXIT_SUCCESS
Assistant
Okay, I have received the second part of your PowerShell script. I have combined the two parts and now have the complete script.
This script is designed to manage a WireGuard tunnel service on a Windows machine, primarily focusing on automatically starting and stopping the service based on whether the current public IP address matches an expected "home" IP address. This is useful for situations where you want the WireGuard tunnel to be active only when you are not on your home network (e.g., when traveling).
Here's a breakdown of what the script does and key aspects:
1. Configuration:
- The script starts with a comprehensive configuration section where you can adjust various parameters:
$ExpectedPublicIP: Your home/ISP's public IP address.$IPCheckURI: A URL that returns your current public IP address in plain text.$TunnelTestIP: An IP address reachable only through the WireGuard tunnel (used for connectivity testing).$WireGuardTunnelName: The name of your WireGuard tunnel configuration file (without the.confextension).- Timeouts, retries, backoff periods, and logging options.
- It dynamically determines the log file path within the current user's "Documents\WireGuardLogs" folder.
2. Logging:
- The script uses a
Write-Logfunction for detailed logging, including timestamps and log levels (INFO, WARN, ERROR). - Log files are rotated daily (or at an interval you configure via
$LogRotationAgeHours).
3. IP Address Detection:
- The
Get-PublicIPfunction retrieves the current public IP address usingInvoke-RestMethod. - It includes retry logic with a configurable timeout and retry delay.
4. Service Management:
Get-WGService,Start-WGService, andStop-WGServicefunctions handle interactions with the WireGuard service.Start-WGServiceincludes a delay ($TunnelStartDelay) after starting the service to allow the tunnel to establish.Stop-WGServiceattempts a clean service stop, but it also has an option ($ForceTerminateOnFailure) to forcefully terminate the WireGuard process if the service fails to stop normally. This is an important feature for reliability.
5. Tunnel Testing:
Test-TunnelUpchecks if the WireGuard tunnel is up and functioning correctly.- It verifies that the WireGuard interface is enabled and pings
$TunnelTestIPto confirm connectivity through the tunnel.
6. Backoff Mechanism:
- The script implements a backoff mechanism using a temporary file (
$BackoffFile). - If the script encounters repeated failures, it enters a backoff period (
$TunnelBackoffHours) during which it will not attempt to start the tunnel. This prevents the script from continuously trying to restart the tunnel in a persistently failing state.
7. Main Logic:
- The script's core logic is based on comparing the current public IP address to the expected IP address (
$ExpectedPublicIP). - If the IPs match (i.e., you are on your home network):
- If the WireGuard service is running:
- It tests if the tunnel is up. If it is, it leaves the service running.
- If the tunnel is not up, it stops the service.
- If the WireGuard service is stopped, it does nothing (it's already in the desired state).
- If the WireGuard service is running:
- If the IPs do not match (i.e., you are not on your home network):
- If the WireGuard service is running:
- It tests if the tunnel is up. If it is, it leaves the service running.
- If the tunnel is not up, it stops the service and attempts to restart it.
- If the WireGuard service is stopped, it attempts to start it (with retries).
- If the WireGuard service is running:
- The script uses exit codes to indicate success or failure, which can be useful for scheduling tasks or monitoring.
Key Improvements/Features in this Version (based on the comments):
- Aggressive Service Cleanup: The script includes logic to forcefully terminate the WireGuard process if the service fails to stop normally. This is crucial for recovering from broken states.
- Connectivity Check: The
Test-TunnelUpfunction now includes a connectivity check (pinging$TunnelTestIP) to ensure the tunnel is actually working. - Backoff Logic: The backoff mechanism prevents the script from continuously retrying in the event of persistent failures.
- Daily Log Rotation: The script rotates log files daily to prevent them from growing too large.
- Single Retry Logic: There's a retry attempt when the script detects a broken tunnel while on the expected IP.
- Preservation of Healthy Tunnels: The script is designed to avoid unnecessary restarts when a tunnel is already up and healthy, even when on the expected IP.
To use this script effectively:
- Install WireGuard: Make sure WireGuard is installed as a Windows service.
- Configure the Script: Carefully configure the variables at the beginning of the script to match your specific setup. Pay close attention to
$ExpectedPublicIP,$IPCheckURI,$TunnelTestIP, and$WireGuardTunnelName. - Schedule the Script: Create a scheduled task to run the script periodically (e.g., every 5-10 minutes). The user account running the scheduled task needs appropriate permissions to manage the WireGuard service.
- Monitor the Logs: Regularly check the log file in the "Documents\WireGuardLogs" folder to ensure the script is running correctly and to diagnose any issues.
This is a well-structured and robust script for managing a WireGuard tunnel based on network conditions. The detailed logging, backoff mechanism, and aggressive cleanup measures make it relatively resilient to network and service disruptions. Remember to configure it carefully for your specific environment.
- The script starts with a comprehensive configuration section where you can adjust various parameters:
- User
change the log location to drive c so when run as system it have the permission
Assistant
Okay, I understand. To change the log location to drive C and ensure the script has the necessary permissions when run as the SYSTEM account, you'll need to modify the script to use a directory on drive C that the SYSTEM account has access to. A common and suitable location is
C:\ProgramData, as this directory is generally accessible by the SYSTEM account.Here's how you should modify the script:
# ======================================================================================= # --- ADJUSTABLE CONFIGURATION PARAMETERS (CHANGE THESE AS NEEDED) --------------------- # ======================================================================================= # (Keep all other configuration parameters the same) # ======================================================================================= # --- DYNAMIC LOG PATHS (AUTO-DETECTED, NO NEED TO CHANGE) ---------------------------- # ======================================================================================= # Modified Log Paths for SYSTEM account compatibility $LogDir = Join-Path -Path "C:\ProgramData" -ChildPath "WireGuardLogs" $LogFile = Join-Path -Path $LogDir -ChildPath "wg_ip_check.log" $BackoffFile = Join-Path -Path $LogDir -ChildPath "wg_backoff.tmp" # Ensure log directory exists (done ONCE at startup) if (-not (Test-Path $LogDir)) { try { New-Item -ItemType Directory -Path $LogDir -Force | Out-Null Write-Host "Created log directory: $LogDir" -ForegroundColor Cyan } catch { Write-Host "Failed to create log directory $LogDir: $($_.Exception.Message)" -ForegroundColor Red #Consider exiting the script here if you can't create the log directory exit # Or another appropriate exit code } }Explanation of Changes:
-
Log Path Modification:
$LogDiris now set toC:\ProgramData\WireGuardLogs.$LogFileand$BackoffFileare updated to reflect the new log directory.
-
Directory Creation with Error Handling:
- The
New-Itemcommand is wrapped in atry...catchblock. This is crucial. Even thoughC:\ProgramDatais generally accessible, there could be unforeseen permission issues. Thetry...catchallows the script to gracefully handle a failure to create the directory. - If the directory creation fails, the
catchblock will output an error message. Consider exiting the script if the log directory cannot be created. Without a log directory, the script's logging will fail, which is essential for troubleshooting.
- The
Important Considerations:
- SYSTEM Account Permissions: The SYSTEM account generally has broad permissions on the local machine, including the ability to create directories and files in
C:\ProgramData. However, Group Policies or other security restrictions could potentially interfere. Thetry...catchblock is designed to catch these scenarios. - Existing Log Files: If you have existing log files in the old location (
$DocumentsPath\WireGuardLogs), they will not be automatically moved. You may want to manually move them if you need to preserve them. - Testing: After making these changes, thoroughly test the script when run as the SYSTEM account (e.g., via the Task Scheduler) to ensure that logging is working correctly. Check that the log file is being created and updated in
C:\ProgramData\WireGuardLogs. - Alternative Locations: If
C:\ProgramDatais not suitable for your environment (due to specific security policies), you could consider other locations likeC:\Windows\Temp, but you will need to carefully evaluate the permissions and security implications of any alternative location.C:\ProgramDatais generally the best choice for service-related data.
Complete Modified Snippet:
I'm including the complete modified snippet here for clarity:
# ======================================================================================= # --- DYNAMIC LOG PATHS (AUTO-DETECTED, NO NEED TO CHANGE) ---------------------------- # ======================================================================================= # Modified Log Paths for SYSTEM account compatibility $LogDir = Join-Path -Path "C:\ProgramData" -ChildPath "WireGuardLogs" $LogFile = Join-Path -Path $LogDir -ChildPath "wg_ip_check.log" $BackoffFile = Join-Path -Path $LogDir -ChildPath "wg_backoff.tmp" # Ensure log directory exists (done ONCE at startup) if (-not (Test-Path $LogDir)) { try { New-Item -ItemType Directory -Path $LogDir -Force | Out-Null Write-Host "Created log directory: $LogDir" -ForegroundColor Cyan } catch { Write-Host "Failed to create log directory $LogDir: $($_.Exception.Message)" -ForegroundColor Red #Consider exiting the script here if you can't create the log directory exit # Or another appropriate exit code } }Make sure to integrate this snippet into your complete script, replacing the original log path definitions and directory creation logic. Remember to test thoroughly after making these changes.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.