Thursday, January 9, 2025

Using SSH on Windows with Powershell

I've come to prefer CLIs over GUIs. Rather than install Putty (or grab the portal version and copy it to the server I want to use), I prefer to SSH directly from Powershell since Microsoft started including a client in the Windows Features.

First, make sure it's installed. From a Powershell prompt running with elevated privileges:

if (-not (Get-WindowsCapability -Online | Where-Object { $_.Name -like 'OpenSSH.Client*' -and $_.State -eq 'Installed' })) {
    Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0
}
This will check if the SSH client is installed and if not, it will install it. 

Using SSH is pretty much the same as it is on Linux then:
ssh <username>@<hostname/fqdn/ip> -p <port>

However, if you do that, you'll be prompted for the password of the user. You could enable key based login, which would essentially use a huge alternate password stored in a file on your computer to connect to the target. 

First make sure your system has a key. If you already have keys, this will overwrite them, so use carefully. You can always change the name to something unique to make sure it doesn't get overwritten. Just update the name in the rest of the commands here. It's the same command on both Linux and Windows.
ssh-keygen -f ~/.ssh/id_rsa -b 4096 -N ""

For Linux
ssh-copy-id -i ~/.ssh/id_rsa.pub -p 22 <username>@<hostname/fqdn/ip>

For Windows
type ~\.ssh\id_rsa.pub | ssh <username>@<hostname/fqdn/ip> "cat >> ~/.ssh/authorized_keys"

Now you should be able to SSH from Powershell using the same command above:
ssh <username>@<hostname/fqdn/ip> -p <port>
Except that now, the client in Powershell will attempt to pass your key to the target to authenticate with. Since you key contains a super-long alternate password, you will be logged in. One cool thing is that this survives password changes on the target account.