Skip to content

Instantly share code, notes, and snippets.

@ctsstc
Last active March 10, 2024 02:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ctsstc/925d2f647e4b943d51027cc9591b0bb9 to your computer and use it in GitHub Desktop.
Save ctsstc/925d2f647e4b943d51027cc9591b0bb9 to your computer and use it in GitHub Desktop.
Update Qbittorrent port on PIA network connection and port forward port

Update Qbittorrent Forward Port from PIA

This script updates the qbittorrent port from the port that PIA returns from its port forwarding if one is available.

This currently only does something if qbittorrent is open and running since it updates through the Web UI. There is commented code that could be changed to utilize the qbittorrent cli to change the port when the application is closed.

Preresiquites

This requires that you have qbittorrent's web interface enabled with the "Bypass authentication for clients on localhost" enabled.

Setup

  1. Save the script update qbittorrent forward port from pia.ps1 to somewhere you'll know where it is for later
    • I put mine under C:\scripts\update-qbittorrent-forward-port-from-pia.ps1
    • Note: The steps below will use the above location as an example
  2. Open Task Scheduler
  3. Create a new folder for organization if you would like (Action -> New Folder).

Importing

  1. Save the XML file below: Update Qbittorrent Forward Port from PIA.xml
  2. Open Task Scheduler
  3. Import Task (right click -> Import Task, or Action -> Import Task)
    • Note: this may require you to have the script saved at: C:\scripts\update-qbittorrent-forward-port-from-pia.ps1

Manual Setup

  1. Create New Task
  2. Give it a meaningful name, maybe even a description
  3. General -> Security Options
    • ☑️ Run whether user is logged on or not
      • ☑️ Do not store password
    • ☑️ Run with highest privledges
  4. Triggers -> New
    • Begin the task: On an event (you can watch the event log for when you toggle the VPN connection)
    • Settings
      • Basic
        • Log: Microsoft-Windows-NetworkProfile/Operational
        • Source: NetworkProfile
        • Event ID: 10000
  5. Actions -> New
    • Action: Start a program
    • Settings
      • Program/script: powershell
      • Add arguments: -ExecutionPolicy Bypass -File "C:\scripts\update-qbittorrent-forward-port-from-pia.ps1"
        • Note: change the path to wherever you saved your script
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
<RegistrationInfo>
<Date>2022-07-04T02:03:04.0327046</Date>
<Author>Coder https://github.com/ctsstc</Author>
<Description>Run script that updates Qbittorrent's forward port from PIA's forwarded port when the network changes and a forwarded port is available.</Description>
<URI>\CTS_AE\Update Qbittorrent Forward Port from PIA</URI>
</RegistrationInfo>
<Triggers>
<EventTrigger>
<Enabled>true</Enabled>
<Subscription>&lt;QueryList&gt;&lt;Query Id="0"
Path="Microsoft-Windows-NetworkProfile/Operational"&gt;&lt;Select
Path="Microsoft-Windows-NetworkProfile/Operational"&gt;*[System[Provider[@Name='Microsoft-Windows-NetworkProfile']
and EventID=10000]]&lt;/Select&gt;&lt;/Query&gt;&lt;/QueryList&gt;</Subscription>
</EventTrigger>
</Triggers>
<Principals>
<Principal id="Author">
<UserId>S-1-5-21-373059960-1286789452-1330396964-1002</UserId>
<LogonType>S4U</LogonType>
<RunLevel>HighestAvailable</RunLevel>
</Principal>
</Principals>
<Settings>
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
<StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
<AllowHardTerminate>true</AllowHardTerminate>
<StartWhenAvailable>false</StartWhenAvailable>
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
<IdleSettings>
<StopOnIdleEnd>true</StopOnIdleEnd>
<RestartOnIdle>false</RestartOnIdle>
</IdleSettings>
<AllowStartOnDemand>true</AllowStartOnDemand>
<Enabled>true</Enabled>
<Hidden>false</Hidden>
<RunOnlyIfIdle>false</RunOnlyIfIdle>
<DisallowStartOnRemoteAppSession>false</DisallowStartOnRemoteAppSession>
<UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine>
<WakeToRun>false</WakeToRun>
<ExecutionTimeLimit>PT1H</ExecutionTimeLimit>
<Priority>7</Priority>
</Settings>
<Actions Context="Author">
<Exec>
<Command>powershell</Command>
<Arguments>-ExecutionPolicy Bypass -File "C:\scripts\update-qbittorrent-forward-port-from-pia.ps1"</Arguments>
</Exec>
</Actions>
</Task>
# Run piactl.exe and get the current open port
function Get-PiaPortForwarded {
# $output = cmd /c "C:\Program Files\Private Internet Access\piactl.exe" $args 2`>`&1
# $output = Get-ProcessOutput -FileName "cmd.exe" -Args "/c ping localhost"
# $output = [string] (cmd /c "C:\Program Files\Private Internet Access\piactl.exe" $args 2>&1)
$output = (cmd /c 'C:\Program Files\Private Internet Access\piactl.exe' get portforward) | Out-String
$output.trim()
}
# Check if the process qbittorrent.exe is running
$process = Get-Process -Name "qbittorrent" -ErrorAction SilentlyContinue
if ($process) {
# We could just kill it and restart it with the correct port
# Instead we'll utilize the the Web API to set the port
# if it is running, kill it
# $process | Stop-Process -Force
# & 'C:\Program Files\qBittorrent\qbittorrent.exe' --torrenting-port=3456
}
else {
# Quit if it's not running
Write-Host "qBittorrent is not running"
exit
}
# if $output is "Inactive" or "Attempting" then wait 2 seconds and try again, stop trying after 10 times and exit
$output = Get-PiaPortForwarded
if ($output -notmatch "^\d+$") {
$i = 0
do {
Write-Host "Port forwarding is '$output' [Trying Again $i/10]"
Start-Sleep -Seconds 2
$output = Get-PiaPortForwarded
$i++
} while (($output -notmatch "^\d+$") -and $i -lt 10)
}
# if $output is not a number then exit
if ($output -notmatch "^\d+$") {
Write-Host "Did not find port forwarding for: '$output'"
exit
}
# if $output is a number then run qBittorrent's API to set the listening port
Write-Host "Found Forwarded Port: $output"
Invoke-WebRequest -Uri "http://localhost:9001/api/v2/app/setPreferences" `
-Method "POST" `
-Body "json=%7B%22listen_port%22%3A%20$output%7D"
Write-Host "Port Forwarding Finished"
# Write-Host "Press any key to continue..."
# $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment