// Help

Add a Windows PC

PocketAdmin reaches a Windows PC over SSH. Windows has its own SSH server, but it's off until someone installs it. One line typed on the PC does that.

Steps

  1. On the PC, open PowerShell as administrator: right-click Start, then choose Terminal (Admin) or Windows PowerShell (Admin).
  2. Type this line, then press Enter:
    irm https://pocketadmin.net/win | iex
  3. In PocketAdmin, tap the Devices tile, then + and New Device. Type the name and address it printed, turn on SSH, and sign in with the username it printed and that Windows account's password. When PocketAdmin shows the PC's identity, it should match one of the lines the script printed.

From PocketAdmin 1.4.1, Devices › + › Add a Windows PC walks you through this, then offers Use a Key Instead: PocketAdmin adds a key of its own on the PC, checks that it signs in, and then forgets the password.

What it does

These four things, and nothing else. Running it again changes nothing that's already done.

  1. Installs OpenSSH Server, Windows' own optional feature, if it isn't installed.
  2. Starts it, and sets it to start with Windows.
  3. Lets SSH (port 22) in from this PC's own network only. If a firewall rule for SSH was already there, it's left as it is.
  4. Makes PowerShell the shell SSH opens, if none is chosen. PocketAdmin's AI speaks PowerShell to Windows.

Then it prints the PC's name, its address, the username to sign in with and the PC's SSH identity.

Check it before it runs

To see what it would do, changing nothing:

& ([scriptblock]::Create((irm https://pocketadmin.net/win))) -Check

To run it only if it's exactly the script on this page (copy this on the PC):

$f = "$env:TEMP\pocketadmin-win.ps1"; irm https://pocketadmin.net/win -OutFile $f; if ((Get-FileHash $f).Hash -eq '701B2750DD6957CA4CC57CA07BCD4E113E2E54A9250D459CB80292A795D8E1B9') { iex (Get-Content $f -Raw) } else { 'This is not the script pocketadmin.net/help/windows shows. Nothing was run.' }

Its SHA-256 is 701b2750 dd6957ca 4cc57ca0 7bcd4e11 3e2e54a9 250d459c b80292a7 95d8e1b9. PocketAdmin shows the start of it beside the line.

The source

All of it, as pocketadmin.net/win serves it:

# PocketAdmin: set up this PC so PocketAdmin can reach it over SSH.
#
# Run it in PowerShell as administrator:
#     irm https://pocketadmin.net/win | iex
# To see what it would do first, changing nothing:
#     & ([scriptblock]::Create((irm https://pocketadmin.net/win))) -Check
# Its source and SHA-256: https://pocketadmin.net/help/windows
#
# It does these four things, and nothing else:
#   1. Installs Windows' own OpenSSH Server, if it isn't installed.
#   2. Starts it, and sets it to start with Windows.
#   3. Lets SSH (port 22) in from this PC's own network only, if no rule lets it in yet.
#   4. Makes PowerShell the shell SSH opens, if none is chosen.
# Then it prints this PC's name, address, login and SSH identity, for the app.
# Run it again and it changes nothing that is already done.
param([switch]$Check)
& {
    param([bool]$Check)
    $ErrorActionPreference = 'Stop'
    function Done($text) { Write-Host "  [done] $text" -ForegroundColor Green }
    function Was($text) { Write-Host "  [ok]   $text" }
    function Would($text) { Write-Host "  [would] $text" -ForegroundColor Yellow }
    function Note($text) { Write-Host "  [note] $text" -ForegroundColor Yellow }

    Write-Host ""
    Write-Host "PocketAdmin: setting up this PC for SSH" -ForegroundColor Cyan
    if ($Check) { Write-Host "  Check only: nothing is changed." }

    $me = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()
    if (-not $me.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
        Write-Host "  This needs PowerShell run as administrator. Right-click Start, choose" -ForegroundColor Yellow
        Write-Host "  Terminal (Admin) or Windows PowerShell (Admin), and run the line again." -ForegroundColor Yellow
        Write-Host "  Nothing was changed." -ForegroundColor Yellow
        return
    }

    # 1. OpenSSH Server, from Windows' own optional features.
    $fresh = $false
    $service = Get-Service sshd -ErrorAction SilentlyContinue
    if ($service) {
        Was "OpenSSH Server is installed."
    } elseif ($Check) {
        Would "install OpenSSH Server (a Windows optional feature)."
    } else {
        Write-Host "  Installing OpenSSH Server. This can take a few minutes..."
        try {
            $feature = Get-WindowsCapability -Online -Name 'OpenSSH.Server*' | Select-Object -First 1
            if ($feature) { Add-WindowsCapability -Online -Name $feature.Name | Out-Null }
        } catch {
            Write-Host "  Windows couldn't install it: $($_.Exception.Message)" -ForegroundColor Red
        }
        $service = Get-Service sshd -ErrorAction SilentlyContinue
        if (-not $service) {
            Write-Host "  OpenSSH Server isn't installed. Add it in Settings > System > Optional features" -ForegroundColor Red
            Write-Host "  (View features > OpenSSH Server), then run this line again." -ForegroundColor Red
            return
        }
        $fresh = $true
        Done "Installed OpenSSH Server."
    }

    # 2. Running, and started with Windows.
    if ($service) {
        if ($service.StartType -eq 'Automatic') { Was "It starts with Windows." }
        elseif ($Check) { Would "set it to start with Windows." }
        else { Set-Service sshd -StartupType Automatic; Done "Set it to start with Windows." }
        if ($service.Status -eq 'Running') { Was "It is running." }
        elseif ($Check) { Would "start it." }
        else { Start-Service sshd; Done "Started it." }
    }

    # 3. The firewall: port 22 from this network only. A rule that was here before is left as it is.
    # Windows calls a new network Public, and the install's own rule covers Private networks only, so a rule
    # that doesn't cover this network's kind doesn't count: one of our own is added beside it.
    $category = [string](Get-NetConnectionProfile -ErrorAction SilentlyContinue | Select-Object -First 1).NetworkCategory
    $kind = @{ 'Public' = 'Public'; 'Private' = 'Private'; 'DomainAuthenticated' = 'Domain' }[$category]
    $builtIn = Get-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -ErrorAction SilentlyContinue
    $ours = Get-NetFirewallRule -Name 'PocketAdmin-SSH-In' -ErrorAction SilentlyContinue
    $covers = $builtIn -and $builtIn.Enabled -eq 'True' -and $builtIn.Action -eq 'Allow' -and
        ($builtIn.Profile.ToString() -eq 'Any' -or -not $kind -or $builtIn.Profile.ToString() -match $kind)
    if ($fresh -and $builtIn) {
        # The rule the install just made lets anyone in, on Private networks only: it is narrowed to this
        # network, on every kind of network.
        Set-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -RemoteAddress LocalSubnet -Profile Any -Enabled True
        Done "Let SSH in from this network only (firewall rule OpenSSH-Server-In-TCP)."
    } elseif ($covers) {
        $from = ($builtIn | Get-NetFirewallAddressFilter).RemoteAddress -join ', '
        if ($from -eq 'LocalSubnet') { Was "SSH is let in from this network only." }
        else {
            Was "A firewall rule lets SSH in (OpenSSH-Server-In-TCP, from: $from). It is left as it is."
            if ($from -eq 'Any') {
                Note "To let SSH in from this network only, run:"
                Note "  Set-NetFirewallRule -Name OpenSSH-Server-In-TCP -RemoteAddress LocalSubnet"
            }
        }
    } elseif ($ours) {
        Was "SSH is let in from this network only (firewall rule PocketAdmin-SSH-In)."
    } elseif ($Check) {
        Would "let SSH in from this network only (a firewall rule)."
    } else {
        New-NetFirewallRule -Name 'PocketAdmin-SSH-In' -DisplayName 'PocketAdmin SSH (this network only)' `
            -Direction Inbound -Protocol TCP -LocalPort 22 -RemoteAddress LocalSubnet -Profile Any -Action Allow | Out-Null
        Done "Let SSH in from this network only (new firewall rule PocketAdmin-SSH-In)."
        if ($builtIn) { Was "The rule OpenSSH-Server-In-TCP is left as it is: it doesn't cover this $kind network." }
    }

    # 4. PowerShell as the shell SSH opens, unless one is chosen already.
    $shell = (Get-ItemProperty 'HKLM:\SOFTWARE\OpenSSH' -Name DefaultShell -ErrorAction SilentlyContinue).DefaultShell
    if ($shell) { Was "SSH opens $shell." }
    elseif ($Check) { Would "make PowerShell the shell SSH opens (it opens cmd.exe now)." }
    else {
        if (-not (Test-Path 'HKLM:\SOFTWARE\OpenSSH')) { New-Item 'HKLM:\SOFTWARE\OpenSSH' | Out-Null }
        $powershell = Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe'
        New-ItemProperty 'HKLM:\SOFTWARE\OpenSSH' -Name DefaultShell -Value $powershell -PropertyType String -Force | Out-Null
        Done "Made PowerShell the shell SSH opens."
    }

    # What the app asks for. The address is the one on the network with the way out (the default gateway).
    $addresses = @(Get-NetIPConfiguration | Where-Object { $_.IPv4DefaultGateway -and $_.NetAdapter.Status -eq 'Up' } |
        Sort-Object { $_.IPv4DefaultGateway[0].RouteMetric } | ForEach-Object { $_.IPv4Address.IPAddress })
    $login = if ($env:USERDOMAIN -and $env:USERDOMAIN -ne $env:COMPUTERNAME) { "$env:USERDOMAIN\$env:USERNAME" } else { $env:USERNAME }
    $microsoft = $false
    try { $microsoft = (Get-LocalUser -Name $env:USERNAME).PrincipalSource -eq 'MicrosoftAccount' } catch { }

    Write-Host ""
    Write-Host "  Type these into PocketAdmin:" -ForegroundColor Cyan
    Write-Host "    Name:     $env:COMPUTERNAME"
    if ($addresses.Count -gt 0) { Write-Host "    Address:  $($addresses[0])" }
    else { Write-Host "    Address:  none found. Is this PC on a network?" }
    if ($addresses.Count -gt 1) { Write-Host "              (also $($addresses[1..($addresses.Count - 1)] -join ', '))" }
    Write-Host "    Username: $login"
    if ($microsoft) { Write-Host "    Password: your Microsoft account's password (not the PIN)" }
    else { Write-Host "    Password: the one you sign in to Windows with (not the PIN)" }

    $keys = @(Get-ChildItem (Join-Path $env:ProgramData 'ssh') -Filter 'ssh_host_*_key.pub' -ErrorAction SilentlyContinue)
    if ($keys.Count -gt 0) {
        Write-Host ""
        Write-Host "  This PC's SSH identity. The app shows one of these when you connect; they should match:" -ForegroundColor Cyan
        foreach ($key in $keys) {
            $parts = (Get-Content $key.FullName -TotalCount 1).Split(' ')
            $hash = [Security.Cryptography.SHA256]::Create().ComputeHash([Convert]::FromBase64String($parts[1]))
            $name = switch -Wildcard ($parts[0]) { 'ssh-ed25519' { 'ED25519' } 'ecdsa-sha2-nistp256' { 'ECDSA P-256' }
                'ecdsa-sha2-nistp384' { 'ECDSA P-384' } 'ecdsa-sha2-nistp521' { 'ECDSA P-521' } 'ssh-rsa' { 'RSA' } default { $parts[0] } }
            Write-Host ("    {0,-12} SHA256:{1}" -f $name, [Convert]::ToBase64String($hash).TrimEnd('='))
        }
    }
    Write-Host ""
} $Check.IsPresent

If it doesn't work

To undo it

In PowerShell as administrator:

Stop-Service sshd; Remove-NetFirewallRule -Name PocketAdmin-SSH-In -ErrorAction SilentlyContinue; Get-WindowsCapability -Online -Name 'OpenSSH.Server*' | Remove-WindowsCapability -Online

If the script made PowerShell the shell SSH opens, that setting stays. To take it out too:

Remove-ItemProperty 'HKLM:\SOFTWARE\OpenSSH' -Name DefaultShell
← TroubleshootingAll help →