PowerShell Port Forwarding Utorrent/Qbittorrent/Other

New Script for pia new api over here
https://www.privateinternetaccess.com/forum/discussion/23542/powershell-port-forwarding-for-utorrent-qbittorrent-other-for-new-api?new=1

I"m not maintaining this script anymore, but it will continue to work until pia stops supporting this method.

I've moved this to it's own disscussion, and some People may find this script useful.   Any question please ask.

Utorrent Script using PowerShell Now With Advance Routing
This scripts change utorrent to listen on port given by pia , 
It uses token support for utorrent and finds which nic to use
automatically.  It refreshes every hour, and generates a new client_id
every time you run the script. It will keep the same client_id the same
as long as it is running. To auto retry reconnect and advance Security
see description below the script.

Known Problems.
1.  Certain symbols in passwords cause issues (ex: $, % and perhaps a few others, but definitely not all!).  If having issues, please use no symbols in the password to eliminate the problem, then add some back in, or don't use symbols in the password.  Thanks
Force, for identifying the issue.
2.  If using autocheck, Please turn off user account control or run as administrator.  It need the private to start and stop the openvpn service.
3. Spaces in windows user names will cause the power shell script not to run if you have the script located on the deskop/documents/etc.  Read this for more info or work around.  This is not a problem with my script but a limitation of  powershell.


#Version 2.31
$USERNAME="piausername"
$PASS="piapassword"
$WEBGUI_HOST="127.0.0.1"
$WEBGUI_USER="utorrentusername"
$WEBGUI_PASS="utorrentpassword"
$WEBGUI_PORT=801
$waittime=0 #how long to wait before starting the script, useful if you need time for the vpn to connect
$ignoressl = $False  #Set to $True when pia has cert problems, not recommended.
$Timer=60 #Wait how many minutes before refreshing port number, default 60
$ENABLEAUTOCHECK = $false # Set to $True to have the service restart to connect to vpn
$EnabledAdvanceRouting = $false  # Set to $True to use this when you have a static ip address and no dns or gateway assigned to your nic
# only works if $Enableautocheck is is $true
$defaultgateway = "yourgatewayipaddress" # Part of Advance routing, change it to your router's ip address
$PIAserver = @()
$PIAservernum = 7 #default $PIAserver you wish to connect to Must enable AdvanceRouting
$PIAserver = @() # List 10 servers to connect to.
$PIAserver += ,@("ca-toronto.privateinternetaccess.com",$true) # First variable is server address, second does it support port forwarding
$PIAserver += ,@("ca.privateinternetaccess.com",$true)
$PIAserver += ,@("ca-toronto.privateinternetaccess.com",$true)
$PIAserver += ,@("nl.privateinternetaccess.com",$true)
$PIAserver += ,@("swiss.privateinternetaccess.com",$true)
$PIAserver += ,@("sweden.privateinternetaccess.com",$true)
$PIAserver += ,@("france.privateinternetaccess.com",$true)
$PIAserver += ,@("us-california.privateinternetaccess.com",$false)
$PIAserver += ,@("us-midwest.privateinternetaccess.com",$false)
$PIAserver += ,@("us-east.privateinternetaccess.com",$false)
$PIAportsnum = 0
$PIAports = @() # pia portcals # the port number of the pia server (udp, 1194, tcp, 443)
$PIAports += ,@("udp", 1194)
$PIAports += ,@("tcp", 443)
$DNSSERVER = "8.8.8.8" # part of Advance Routing, use any dns server, the default is google dns 8.8.8.8
$pathtoovpn = "C:\Program Files\OpenVPN\config\pia.ovpn" # path to pia opvn file, this scripts edits the file and adds piaserver ip address, change to match yours ovpn location
$disableportforward = $False # to temporary disable port forwarding when connected to a non-port forwarding server
#Script below,  be careful changing anything below this line
$Windowswidth = 100
$WindowsHeight = 25
$host.ui.RawUI.WindowTitle = "PIA Port Forwarding for Utorrent"
$rand = New-Object  System.Random
$chrstg = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ1234567890"
$CLIENT_ID =""
1..100 | % {$CLIENT_ID += $chrstg.substring($rand.next(0,$chrstg.length),1) }
$count = 0
$problemdetected = $false
$servererror = $false
$url="http://" + $WEBGUI_HOST + ":" + $WEBGUI_PORT + "/gui/"
$saveX = [console]::CursorLeft 
$saveY = 0
$strmoving = '|','/','-','\'   
$startline = 2 #which line to start updating on
$emptyspaces = ""
1..$Windowswidth | % {$emptyspaces += " " }
$utorrentfound = $false
$Fullscreenclear = $false
function clearscreen ($start, $fullclear = $false) {
    if ($fullclear) {
        clear;
        printsettings;
        [console]::SetCursorPosition($savex,$start)
    } else {
        [console]::SetCursorPosition($savex,$start)
        for ($i=$start; $i -le 6;$i++) {Write-host $emptyspaces}
        [console]::SetCursorPosition($savex,$start)
    }
    $Fullscreenclear = $false
}
function printsettings(){
    write-host "Enabled Auto Check is set to:$ENABLEAUTOCHECK"
    write-host "Enable Advance Routing is set to:$EnabledAdvanceRouting"
}

function isNumeric ($x) {
    $x2 = 0
    $isNum = [System.Int32]::TryParse($x, [ref]$x2)
    return $isNum
}

Function listservers{
    $SaveY=[Console]::CursorTop
    [console]::SetCursorPosition($saveX,$SaveY+4)
    for ($i = $PIAserver.getlowerbound(0);$i -le $PIAserver.getupperbound(0); $i++){
        $temp = " $i  " +  $PIAserver[$i][0] + $emptyspaces
        write-host $temp.substring(0,45) "Port Forwarding="$PIAserver[$i][1]
    }
    #Start-Sleep -s 5
    [console]::SetCursorPosition($saveX,[Console]::$SaveY)

}
Function AdvanceRouting{
    write "Flushing DNS cache"
    ipconfig /flushdns
    write "Adding temporary route for DNS Server:$DNSSERVER by gateway:$defaultgateway"
    route add $DNSSERVER mask 255.255.255.255 $defaultgateway
    $FullAddressList = nslookup -type=a $PIAserver[$PIAservernum][0] $DNSSERVER
    write "Deleting temporary route to DNS Server:$DNSSERVER by gateway:$defaultgateway"
    route delete $DNSSERVER
     if (test-path $pathtoovpn) {
        foreach ($line in $FullAddressList)    {
            $tempip = "$line" | %{ $_.Split(" ")[2] }
            $tempport = $PIAports[$PIAportsnum][1]
            $tempportocall = $PIAports[$PIAportsnum][0]
            $IsValid = ($tempip -As [IPAddress]) -As [Bool]
            if ($IsValid -and $tempip -ne $DNSSERVER){
                write "Adding temporary route for PIA Server:$tempip by gateway:$defaultgateway"
                route add $tempip mask 255.255.255.255 $defaultgateway
                (gc $pathtoovpn) -replace 'remote .*', "remote $tempip $tempport " | sc $pathtoovpn
                (gc $pathtoovpn) -replace 'proto .*', "proto $tempportocall" | sc $pathtoovpn
                write "Updating File:$pathtoovpn to connect to PIA Server"
                write "with ip address:$tempip  $tempportocall $tempport"
                return
            }
        }
        write "Not a valid DNS Server, or not a valid gateway, or not a valid PIA Server address"
        Start-Sleep -s 60
    } else {
        write-host "Not a valid path to openvpn config file:$pathtoovpn"
        Start-Sleep -s 60
    }
  
}
function setwindowsize {
    $pshost = get-host
    $pswindow = $pshost.ui.rawui
    $psWindow.WindowSize = @{Width=1; Height=1}
    $psWindow.BufferSize = @{Width=$Windowswidth; Height=$WindowsHeight}
    $psWindow.WindowSize = @{Width=$Windowswidth; Height=$WindowsHeight}
   
}
setwindowsize
printsettings

if ($waittime -gt 0) {
    Write-host "Waiting $waittime seconds before continuing"
    Start-Sleep -s $waittime
}

if ($ignoressl) { [System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }}
$disableportforward = !$PIAserver[$PIAservernum][1]
while($true) {
    try {
        $ip = (Get-WmiObject -Class Win32_NetworkAdapterConfiguration | Where-Object {$_.Description -like "TAP*"}).IPAddress[0]
    }
    catch [system.exception] {
        $a = get-date
        if ($ENABLEAUTOCHECK) {
              
               clearscreen $startline  $True
               Write-Host $a.toshorttimestring() "VPN is not connected. Restarting service (60 Seconds) "
            Stop-Service OpenVPNService
            if ($EnabledAdvanceRouting) {
                clearscreen $startline  $True
                Write-Host $a.toshorttimestring() "Advance Routing Enabled, Resetting up routes to connects to PIA Server"
                AdvanceRouting
            }
            Start-Service OpenVPNService
            $problemdetected = $true
            write "Waiting 60 seconds for openvpn to connect"
            Start-Sleep -s 60
            clearscreen $startline $True
        } else {
            Write-Host $a.toshorttimestring() "VPN is not connected. Checking again in 1 minute."
            Start-Sleep -s 60
        }
        continue
    }
       $ProcessActive = Get-Process uTorrent -ErrorAction SilentlyContinue
    if(($ProcessActive -eq $null -and ($count % $timer -eq 0)) -or $disableportforward -or $ProcessActive -eq $null) {
        clearscreen $startline
        $a= get-date
        if (!$disableportforward){
            Write-host $a.toshorttimestring() "uTorrent is not running. Checking again in 1 minute."
        } else {
            Write-host $a.toshorttimestring() "You are currently connected to pia server" $PIAserver[$PIAservernum][0] $PIAports[$PIAportsnum][0]
            Write-host $a.toshorttimestring() "Port forwarding is disabled"
            Write-host $a.toshorttimestring() "Checking every minute to see if your connected"
            $problemdetected = $True
        }
               
    } elseif ((($count % $timer -eq 0) -or  $problemdetected)) {
        try {
            $a= get-date
            $response = $null
            $servererror = $true
            $web = New-Object System.Net.WebClient
            $Web.Headers.Add("User-Agent", "User-Agent: Mozilla/5.0")
            $web.Headers.Add("Content-Type","application/x-www-form-urlencoded")
            $response = $web.UploadString("https://www.privateinternetaccess.com/vpninfo/port_forward_assignment","user=$USERNAME&pass=$PASS&client_id=$CLIENT_ID&local_ip=$ip")
            if ($response::IsNullOrEmpty ) {
                Write-Host $a.toshorttimestring() "Did not get a response from the server. Retrying in 1 minute."
            } else {
                $port = $response.Substring(8,$response.IndexOf("}")-8)
                if (isNumeric ($port) ) {
                    clearscreen ($startline)
                    Write-Host "Port given is $port"
                    $count = 0
                    $servererror = $false
                } else {
                    clearscreen ($startline)
                    Write-Host $a.toshorttimestring() "Server returned an error,  Retrying in 1 minute."
                    Write-Host $a.toshorttimestring() $response
                    Write-host $a.toshorttimestring() "You are currently connected to pia server" $PIAserver[$PIAservernum][0]
                }
            }
            if ($servererror) {Start-Sleep -s 60}
        }
        catch [system.exception] {
            clearscreen ($startline)
            $a= get-date
            Write-Host $a.toshorttimestring() "Unable to connect to remote host. Retrying in 1 minute."
            $error[0].ToString() + $error[0].InvocationInfo.PositionMessage
            Start-Sleep -s 60
            continue
        }
    
        if (!$servererror) {
            try {
                $web = New-Object System.Net.WebClient
                $CookieContainer = New-Object System.Net.CookieContainer
                $web.Credentials = New-Object System.Net.NetworkCredential($WEBGUI_USER,$WEBGUI_PASS)
                $response = $web.DownloadString($url+"token.html")
                $cookies =  $web.ResponseHeaders["Set-Cookie"]
                $web.Headers.Add("Cookie", $cookies)
                $token = $response.split('>')[2].split('<')[0]
                $response = $web.DownloadString($url+"?action=setsetting&s=bind_port&v=$port&token=$token")
                $response = $web.DownloadString($url+"?action=getsettings&token=$token")
                $problemdetected = $flase
                $a = get-date
                $a = $a.Addminutes($timer)
                clearscreen ($startline + 1)
                $response= ($Response.substring($Response.indexof("bind_port")-1)).substring(14)
                Write-Host "Utorrent set to=" $response.Substring(0,$Response.indexof(","))
                Write-Host "Sleeping until an update is needed again at at"  $a.toshorttimestring()
               }
            catch [system.exception] {
                clearscreen ($startline + 1)
                $a = get-date
                Write-Host $a.toshorttimestring() "Failed to update port via uTorrent WEBGUI."
                write-Host "Please check the information you've given this script."
            }
        }
    }
    $saveY =  [console]::CursorTop
    if ($EnabledAdvanceRouting) {
        Write-Host "Press 'q' to quit, 'p' to enable/disabled port forwarding, "
        Write-Host "'r' to stop and reconnect to pia, 'l' to list pia severs, 't' to change protocols"
        Write-Host "'0-9' to connected to a different pia server, or any other key to refresh"
       
    } else {
        Write-Host "Press 'q' to quit, 'p' to enable/disabled port forwarding, "
        Write-Host "or any other key to refresh"
    }
    $counter = 0
    while(!$Host.UI.RawUI.KeyAvailable -and $counter++ -le  60 ) {
        $strmoving | ForEach-Object {
            Write-Host -Object $_ -NoNewline
            [Threading.Thread]::Sleep( 200 )
            [console]::SetCursorPosition($saveX,[Console]::CursorTop)
        }
    }
    if ($Host.UI.RawUI.KeyAvailable) {
        $key = $host.UI.RawUI.ReadKey('NoEcho,IncludeKeyUp')
        if ($key.character -eq "Q") {break;}
        if ($key.character -eq "P" -and $EnabledAdvanceRouting) {$disableportforward=!$disableportforward;}
        if ($key.character -eq "R" -and $EnabledAdvanceRouting) {write-Host "Stopping OpenVPNService";Stop-Service OpenVPNService;Start-Sleep -s 10}
        if ($key.character -eq "T" -and $EnabledAdvanceRouting) {
            if ($PIAportsnum -eq 0) {
                $PIAportsnum = 1   
                } else {
                $PIAportsnum = 0
            }
            write-Host "Changing Protocol to " $PIAports[$PIAportsnum][0]
            write-Host "Stopping OpenVPNService"
            Stop-Service OpenVPNService;
            Start-Sleep -s 10
        }
   
        if (isnumeric($key.character) -and $EnabledAdvanceRouting) {
            $PIAservernum = [convert]::ToInt16($key.character, 10)
            write-Host "Stopping OpenVPNService and Changing Servers to"  $PIAserver[$PIAservernum][0]
            Stop-Service OpenVPNService
            $disableportforward = !$PIAserver[$PIAservernum][1]
            Start-Sleep -s 10
        }
       
        if ($key.character -eq "L" -and $EnabledAdvanceRouting) {listservers;}
        [Threading.Thread]::Sleep(500)
        $Host.UI.RawUI.FlushinputBuffer()
        $problemdetected = $true
         
    } else {
        clearscreen $savey
    }
    $count +=1
}



V 1.01 updated to scripted powershell is working again on pia 2/1/13
V 1.02 fix a clientid issues, where stopping and string scripts cause the clinetid to grow  +100 characters
V
1.03 fix next refresh, combind the two scripts, added $ENABLEAUTOCHECK,
fix time for next refresh, and manual refresh and quit option.
V1.11
fix problem with virtual machine pausing the scripting on keydown,
added debug info option, and rotating star to see that it is still
running, also, no longer scrolls.
V1.12 fix problem with clearing screen, auto reconnect works betters
V1.13 added time info on messages
V1.14 fix a variable problem
V1.15
added useragent to fix pia recent change, you got an error "The
underlying connection  was closed: An unexpected error occurred on a
receive."  Also added option to ignore ssl errors, when pia has cert
problems.
V1.16 Check to make sure a valid port was given before trying utorrent update, other minor fixes.
V1.17 Clean up code, debug, etc
V1.18 Cleaned up debug code, add help info
V1.19 fix random client id excluding first character is string.
V1.20 Display Utorrent name in response
V1.21 Read Utorrent preference and show Utorrent settings.
V1.22 Cleaned up Utorrent response that shows what Utorrent is set to.
V1.23 Add optional delay before starting script, also changed powershell title
V2.00 Added option to run with Advance Security
V2.1 Fix spelling, change Advance Security to Advance Routing
V2.2 Add the ability to disable port forwarding, and change servers.
V2.3  Allow you to change vpn protocals
V2.31 Fix the buffer issies people were having

$ENABLEAUTOCHECK
to enable this set
 $ENABLEAUTOCHECK = $true
If
you set openvpn to run as a service, and this is $true, it will check
every minute to make sure you are connected, if not it will try to
reconnect you every two minutes.

Go to this website for more info on openvpn service  http://vpnblog.info/openvpn-startup-windows.html.
Basically do this.

The Windows installer will set up a Service Wrapper, but leave it turned off by default. We need enable OpenVPN service and make sure it's set to Startup Type to manual. The script will start it and monitor it.

1) Open Control Panel -> Administrative Tools
2) Find and open Services
3) Find OpenVPN Service, right mouse click and Properties4) Set Startup type to Manual
5) When you started computer, the OpenVPN Service Wrapper will scan the \Program Files\OpenVPN\config ( for 64 bit OS \Program Files(x86)\OpenVPN\config ) folder for .ovpn configuration files and starting a separate OpenVPN process on each file( So only have one in there).

Once OpenVPN started as a service on Windows, the only way to control it is in Services, right mouse click on OpenVPN service and it gives start/stop control.

 $EnabledAdvanceRouting = $true

What
is this, this is when you set your nic to a static ip address, and
don't assign a dns or gateway to the nic.  Basically your computer
doesn't know how to get to the internet.  What this does it adds a
temporary route to a dns server and looks up pia server address.  it
then remove the route to the dns server and adds a route so your
computer knows how to connect to the pia server.  In then updates
openvpn connection file and adds the ip address.  then openvpn is able
to connect.

Why this?  if your computer doesn't know how to
connect to the internet, apps can't leak your real ip address, ex
Utorrent.  so you can't get on the internet until openvpn connects,and
if the connection drops, your back to no internet.

Here the steps to get this to work.

1. install openvpn, (update the path $pathtoovpn if you installed the 64bit version)
2. copy one pia openvpn config to the config directory, rename it to pia
3. make an authpass.txt, first line your username, second line your password
4. edit pia.ovpn file add these three lines
auth-user-pass authpass.txt
route-metric 512
route 0.0.0.0 0.0.0.0

5. Set the openvpn service to manual in services.msc
6. edit the default gateway variable and set it your router
7. change the PIA server variable if you want to connect to a different server
8. Make sure the openvpn service is set to manual

You should be good to go, just put the script in startup and when your computer starts up it will connect to pia.

Comments

  • edited February 2016
    Updated to work with Qbittorrent 3.2 and above
    qBittorrent script using powershell.
    This scripts change qBittorent to listen on port given by pia , 
    It finds the openvpn nic to use automatically and connects on that ip address.  You can lock qBittorrent down to that nic.  It refreshes every hour, and generates a new client_id
    for privacy every time you open the script. It will keep the same
    client_id  as long as the powershell script is running. To auto retry reconnect see
    my earlier post on page 2 regarding Utorrent.

    Known Problems.
    1. Certain symbols in a passwords cause issues (ex: $, % and perhaps a few others, but definitely not all!).  If having issues use no symbols in the password to eliminate the problem, then add some back in, or don't use symbols in the password.  Thanks Force for identifying the issue.
    2.  If using autocheck, Please turn off user account control or run as administrator.  It need the private to start and stop the openvpn service.
    3. Spaces in windows user names will cause the power shell script not to run if you have the script located on the deskop/documents/etc.  Read this for more info or work rounds.  This is not a problem with my script but a limitation of  powershell.



    #Version 1.05
    $USERNAME="piausername"
    $PASS="piapassword"
    $WEBGUI_USER="qbittorrentusername"
    $WEBGUI_PASS="qbittorrentpassword"
    $WEBGUI_PORT=0 #Change this to qbittorrent web port number
    $ENABLEAUTOCHECK = $False # Set to $True to have the service restart to connect to vpn
    $ignoressl = $False  #Set to $True when pia has cert problems, not recommended.
    $Timer=60 #Wait how many minutes before refreshing port number, default 60
    $host.ui.RawUI.WindowTitle = "PIA port forward for qBitTorrent"
    $rand = New-Object  System.Random
    $chrstg = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
    $CLIENT_ID =""
    1..100 | % {$CLIENT_ID += $chrstg.substring($rand.next(0,$chrstg.length),1) }
    $count = 0
    $problemdetected = $false
    $servererror = $false
    write-host "Enabled Auto Check is set to:"$ENABLEAUTOCHECK
    $saveY = 4
    $saveX = [console]::CursorLeft  
    $debugy = 6
    $currenty = 1
    $strmoving = '|','/','-','\'    

    function clearscreen ($start) {
        [console]::SetCursorPosition($savex,$start)
        for ($i=$start; $i -le 10;$i++)
        {Write-host "                                                                                  "}
        [console]::SetCursorPosition($savex,$start)
    }
    function isNumeric ($x) {
        try {
            0 + $x | Out-Null
            return $true
        }
        catch { return $false }
    }
    if ($ignoressl) { [System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }}
    while($true) {
        try {
            $ip = (Get-WmiObject -Class Win32_NetworkAdapterConfiguration | Where-Object {$_.Description -like "TAP*"}).IPAddress[0]
            }
        catch [system.exception] {
            clearscreen (1)
            $a = get-date
            if ($ENABLEAUTOCHECK) {
                   Write-Host $a.toshorttimestring() "VPN is not connected. Restarting service (2 minutes) "
                Restart-Service OpenVPNService
                $problemdetected = $true
                Start-Sleep -s 120
            } else {
                Write-Host $a.toshorttimestring() "VPN is not connected. Checking again in 1 minute."
                Start-Sleep -s 60
            }
            continue
        }
        $ProcessActive = Get-Process qbittorrent -ErrorAction SilentlyContinue
        if($ProcessActive -eq $null -and ($count % $timer -eq 0)) {
            clearscreen (1)
            $a= get-date
            Write-host $a.toshorttimestring() "qBittorrent is not running. Checking again in 1 minute."
            Start-Sleep -s 60
            continue
        } elseif (($count % $timer -eq 0) -or  $problemdetected) {
            try {
                $a= get-date
                $response = $null
                $servererror = $true
                $web = New-Object System.Net.WebClient
                $Web.Headers.Add("User-Agent", "User-Agent: Mozilla/5.0")
                $web.Headers.Add("Content-Type","application/x-www-form-urlencoded")
                $response = $web.UploadString("https://www.privateinternetaccess.com/vpninfo/port_forward_assignment","user=$USERNAME&pass=$PASS&client_id=$CLIENT_ID&local_ip=$ip")
                if ($response::IsNullOrEmpty ) {
                    Write-Host $a.toshorttimestring() "Did not get a response from the server. Retrying in 1 minute."
                } else {
                    $port = $response.Substring(8,$response.IndexOf("}")-8)
                    if (isNumeric ($port) ) {
                        clearscreen (1)
                        Write-Host "Port given is $port"
                        $count = 0
                        $servererror = $false
                    } else {
                        clearscreen (1)
                        Write-Host $a.toshorttimestring() "Server returned an error,  Retrying in 1 minute."
                        Write-Host $a.toshorttimestring() $response
                    }
                }
                if ($servererror) {Start-Sleep -s 60}
            }
            catch [system.exception] {
                clearscreen (1)
                $a= get-date
                Write-Host $a.toshorttimestring() "Unable to connect to remote host. Retrying in 1 minute."
                $error[0].ToString() + $error[0].InvocationInfo.PositionMessage
                Start-Sleep -s 60
                continue 
            }
         
            if (!$servererror) {
                try {
                    $url="http://" + $ip + ":" + $WEBGUI_PORT
                    $web = New-Object System.Net.WebClient
                    $postParams = "username=$WEBGUI_USER&password=$WEBGUI_PASS"
                       $response = Invoke-WebRequest -Uri $url"/login" -Method POST -Body $postParams
                    $Headers = $response.headers | out-string -width 4096
                    $Headers =  $Headers.substring($Headers.indexof("SID")-1)
                    $Headers =  $Headers.substring(0,$Headers.indexof(";"))
                    $web.Headers.Add("Cookie", $Headers)
                    $web.Headers.Add("Content-Type","application/x-www-form-urlencoded")
                    $postData = 'json={"listen_port":' + $port + '}'
                    [byte[]]$byteArray = [System.Text.Encoding]::ASCII.GetBytes($postData)
                    $Response= $web.UploadData($url + "/command/setPreferences", "POST", $byteArray)
                    $Response= $web.DownloadString($url + "/query/preferences")
                    $problemdetected = $flase
                    $a = get-date
                    $a = $a.Addminutes($timer)
                    clearscreen (2)
                    $qbport = ($Response.substring($Response.indexof("listen_port")-1))
                    $qbport = $qbport.substring(0,$qbport.indexof(","))
                    Write-Host "qBitTorrent set to=" $qbport
                    Write-Host "Sleeping till update is needed again at at"  $a.toshorttimestring()
                    Write-Host "Press q to quit or any key to refresh"
                    $response = $web.DownloadString($url + "/logout")
                }
                catch [system.exception] {
                    clearscreen (2)
                    $a = get-date
                    Write-Host $a.toshorttimestring() "Failed to update port via qBitTorrent WEBGUI."
                    write-Host "Please check the information you've given this script."
                }
            }
        }
        $counter = 0
        while(!$Host.UI.RawUI.KeyAvailable -and $counter++ -le  60 ) {
            $strmoving | ForEach-Object {
                Write-Host -Object $_ -NoNewline
                [Threading.Thread]::Sleep( 200 )
                [console]::SetCursorPosition($saveX,5)
            }
        }
        if ($Host.UI.RawUI.KeyAvailable) {
            $key = $host.UI.RawUI.ReadKey('NoEcho,IncludeKeyUp')
            if ($key.character -eq "Q") {break;}
               [Threading.Thread]::Sleep(500)
               $Host.UI.RawUI.FlushinputBuffer()
               $problemdetected = $true
        }
        $count +=1
    }

    #v1.00 First working version of this script
    #v1.01 fix random client id excluding first character is string.
    #v1.02 fix, to work with qBitorrent 3.2 and above, older version will not work
    #v1.03 Added optional delay to start script, changed powershell title
    #v1.04 fix display of port settings.
    #v1.04b changed default timer setting to 60 was 0.
    #v1.05 Fix spelling mistake, thanks p6589306
  • Place holder
  • Place holder
  • I'm kind of a newb, could you help me with this script but have it update Transmission?
  • edited December 2015
    pyrostic said:
    I'm kind of a newb, could you help me with this script but have it update Transmission?
    I thought Transmission was a Mac application. Are you using it on Linux via GTK+ or Qt?

    I do not think any of this really applies to Mac systems.

    And since I have never owned a Mac, I cannot really offer any help. Sorry.
    *Edit* Reworded the post for clarity.
  • Transmission-QT
    http://sourceforge.net/projects/trqtw/

    However I'm attempting to get either of the above to work with qbittorrent and utorrent. I'm having an issue with the buffersize command in the utorrent script as it says it is too large.
  • I do not have a means to try this, but you can change the following line as follows.
        $pswindow.buffersize = $newsize
        $pswindow.buffersize = $0

    I do not know if it will accept a specific value or not, and it may just crash with it set to zero. But I would try that first and then try increasing to 1024, 4096, 16384, 262,144 and so on. One of those is likely to work. And I cannot imagine it needs much.

    Since "newsize" is not defined, it is deciding how much outside of this script. So specifying how much may work, but may also be buggy and difficult to fix. If it can accept a specific value provided like this, then the problem is easy to fix by trial and error.

    I can only wish you luck.
  • edited December 2015
    yeah thats not working.

    Exception setting "buffersize": "Cannot set the buffer size because the size specified is too large or too small.
    Parameter name: value
    Actual value was 100,3000."

    is the specific error
    Alright I've solved 99% of my issue by calling the powershell script through an elevated batch file. Now to find a utorrent version that will get updated properly...
  • edited December 2015
    What version of UTorrent is this compatible with? I've installed the webui, however it won't update the port.
  • yeah thats not working.

    Exception setting "buffersize": "Cannot set the buffer size because the size specified is too large or too small.
    Parameter name: value
    Actual value was 100,3000."

    is the specific error
  • I currently use it with 3.2.1.  It shoudl work with anything that supports webui.  You can safely ignore the buffer-size, all this does it resize the window to make it look nice, you can resize it manually for testing purpose. 
    I'm currently running this script on Windows 7, with uac off.
  • Can somebody help me with an issue with the script? When I run it, i get an error: 

    Enabled Auto Check is set to: False
    Attempted to divide by zero.
    At F:\Untitled1.ps1:64 char:15
    +     } elseif (($count % $timer -eq 0) -or  $problemdetected) {
    +               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    /   + CategoryInfo          : NotSpecified: (:) [], RuntimeException
        + FullyQualifiedErrorId : RuntimeException
  • Which script are you using? Utorrent, or Qbitorrent?  Can you post your settings(just change your username and password).  Did you change anything in the script?
  • By settings, do you mean your script settings? 
    I'm using qbittorrent 3.3.1 on Windows 10...

    #Version 1.04
    $USERNAME="aaaaaaaa"
    $PASS="aaaaaaaa"
    $WEBGUI_USER="admin"
    $WEBGUI_PASS="aaaaaaaaaa"
    $WEBGUI_PORT=8080 #Change this to qbittorrent web port number 
    $ENABLEAUTOCHECK = $true # Set to $True to have the service restart to connect to vpn
    $ignoressl = $False  #Set to $True when pia has cert problems, not recommended.
    $Timer=0 #Wait how many minutes before refreshing port number, default 60
    $host.ui.RawUI.WindowTitle = "PIA port forward for qBitTorrent"
    $rand = New-Object  System.Random
    $chrstg = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
    $CLIENT_ID =""
    1..100 | % {$CLIENT_ID += $chrstg.substring($rand.next(0,$chrstg.length),1) }
    $count = 0
    $problemdetected = $false
    $servererror = $false
    write-host "Enabled Auto Check is set to:"$ENABLEAUTOCHECK
    $saveY = 4
    $saveX = [console]::CursorLeft   
    $debugy = 6
    $currenty = 1
    $strmoving = '|','/','-','\'  

    The only things I changed in the script are 
    $USERNAME="aaaaaaaa"
    $PASS="aaaaaaaa"
    $WEBGUI_USER="admin"
    $WEBGUI_PASS="aaaaaaaaaa"
    $WEBGUI_PORT=8080

    Thanks for your help

  • gtharea said:

    $Timer=0 #Wait how many minutes before refreshing port number, default 60


    Change the $Timer=0 to $Timer=60.  I've updated the script to reflect the default value.
  • edited February 2016
    pyrostic said:
    yeah thats not working.

    Exception setting "buffersize": "Cannot set the buffer size because the size specified is too large or too small.
    Parameter name: value
    Actual value was 100,3000."

    is the specific error
    Fixed it use the updated script 3.21


  • It's not working for me qbittorrent 3.3.3, im using openvpn GUI and im not using the openVPN service, is it REQUIRED to use the openvpn service for the qbittorrent version?
  • Looks like the script itself is broken because when I save the following as an HTML file and run it, i do get a port response, but nothing i could do would give me a response through the script, even disabling my firewalls did not work, here is the html code:

    <html>
    <head>
    <title>PIA Port Forward Request</title>
    </head>
    <body>
    <form name="myform" action="https://www.privateinternetaccess.com/vpninfo/port_forward_assignment" method="POST">
    <div align="center">
    <br><br>
    <input type="text" name=user size="25" value="USERNAME">
    <input type="text" name=pass size="25" value="PASSWORD">
    <input type="text" name=client_id size="25" value="garbage">
    <input type="text" name=local_ip size="25" value="LOCAL_IP">
    <br><input type="submit" value="Request Port"><br>
    </div>
    </form>
    </body>
    </html>
  • edited February 2016
    p6589306 said:
    It's not working for me qbittorrent 3.3.3, im using openvpn GUI and im not using the openVPN service, is it REQUIRED to use the openvpn service for the qbittorrent version?

    For the qbittorrent version openvpn services not required, but openvpn is used and requiered as it needs the ip address.  It gets this by searching for the "Tap" network adapter.

  • scripting said:
    p6589306 said:
    It's not working for me qbittorrent 3.3.3, im using openvpn GUI and im not using the openVPN service, is it REQUIRED to use the openvpn service for the qbittorrent version?

    For the qbittorrent version openvpn services not required, but openvpn is used and requiered as it needs the ip address.  It gets this by searching for the "Tap" network adapter.

    I debugged your script, it seems to be running just fine and returning a port just fine, and despite this it's returning the error "Did not get a respond from the server. Retrying in 1 minute."... I found this out by adding a write-host $response line, and it displayed the port correctly then spat out the "did not get a respond" error....

    I found this line to be the problem: if ($response::IsNullOrEmpty) {
    I changed it to: if ([string]::IsNullOrEmpty($response)) {    
    and now it works...
    But I'm not a coder and I don't know if this code is correct or not, ie I'm not 100% sure if its actually seeing if $response inNullOrEmpty or not, all i know is that at this point the code continues and the port gets updated in qbittorrent correctly and everything works fine... Let me know if my code edit is correct or not.
  • One last thing, your script does not work for people who's windows login name has a space in it... for example if my login was "john doe" and my user folder was C:/users/john doe/whatever.... the script will return an error that it cannot find C:/users/john  because it doesn't see anything past the space. I got around the issue by putting the script in the C: folder and executing it there so there are no spaces to deal with, but would be nice to have it part of the script so users can execute it in a path that contains a space.
  • edited February 2016
    p6589306 said:
    One last thing, your script does not work for people who's windows login name has a space in it... for example if my login was "john doe" and my user folder was C:/users/john doe/whatever.... the script will return an error that it cannot find C:/users/john  because it doesn't see anything past the space. I got around the issue by putting the script in the C: folder and executing it there so there are no spaces to deal with, but would be nice to have it part of the script so users can execute it in a path that contains a space.
    That's a known powershell problem, read this for work around. This is not something I can fix within the script and without making changes to global powershell properties, which I smothering I don't want to do that.


  • edited February 2016
    p6589306 said:
    scripting said:
    p6589306 said:
    It's not working for me qbittorrent 3.3.3, im using openvpn GUI and im not using the openVPN service, is it REQUIRED to use the openvpn service for the qbittorrent version?

    For the qbittorrent version openvpn services not required, but openvpn is used and requiered as it needs the ip address.  It gets this by searching for the "Tap" network adapter.

    I debugged your script, it seems to be running just fine and returning a port just fine, and despite this it's returning the error "Did not get a respond from the server. Retrying in 1 minute."... I found this out by adding a write-host $response line, and it displayed the port correctly then spat out the "did not get a respond" error....

    I found this line to be the problem: if ($response::IsNullOrEmpty) {
    I changed it to: if ([string]::IsNullOrEmpty($response)) {    
    and now it works...
    But I'm not a coder and I don't know if this code is correct or not, ie I'm not 100% sure if its actually seeing if $response inNullOrEmpty or not, all i know is that at this point the code continues and the port gets updated in qbittorrent correctly and everything works fine... Let me know if my code edit is correct or not.


    I just tested the script and it works.  What you did is to bypass that check to make sure pia responded.  This will work fine until pia doesn't respond, then the script will break. 

    I would copy the script again and set your variables again.
    Did the script give you any errors, what was the scripts output or qbittorrent not updating?
  • Once i bypassed the PIA check everything works great... what is happening is that the script thinks it is not getting a response from the server when it actually is getting a response...

    I put write-host $response in the script just before the error and it would print the port (Because write-host $response) then proceed to say "Did not get a respond from the server. Retrying in 1 minute.", which does not make any sense...  because if it's getting a port from PIA it shouldn't say that... it's saying that despite getting a port from PIA for me... which is really strange. Bypassing that check makes the script work 100% for me.

    If you're asking me for the output, the script will say "Did not get a respond from the server. Retrying in 1 minute." and qbittorrent will not update" but if i bypass that part, it works fine, and the port updates correctly.

    I tried copying the variables again and it did th same thing. If you like I can give you my contact information via PM and you can access my system through remote control to take a look. up to you.

  • p6589306 said:
    Once i bypassed the PIA check everything works great... what is happening is that the script thinks it is not getting a response from the server when it actually is getting a response...

    I put write-host $response in the script just before the error and it would print the port (Because write-host $response) then proceed to say "Did not get a respond from the server. Retrying in 1 minute.", which does not make any sense...  because if it's getting a port from PIA it shouldn't say that... it's saying that despite getting a port from PIA for me... which is really strange. Bypassing that check makes the script work 100% for me.

    If you're asking me for the output, the script will say "Did not get a respond from the server. Retrying in 1 minute." and qbittorrent will not update" but if i bypass that part, it works fine, and the port updates correctly.

    I tried copying the variables again and it did th same thing. If you like I can give you my contact information via PM and you can access my system through remote control to take a look. up to you.

    Can you post "write-host $response" response.  Also what gateway are you connecting to.
Sign In or Register to comment.