Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect to linux server using ssh with private key from PowerShell?

I have generated an ssh key pair using puttygen and can successfully connect to my CentOS server with my private key from putty on my Windows 10 workstation:

image of successful connection to CentOS

I want to connect to the server from Windows PowerShell and have loaded the Posh-SSH module with Install-Module posh-ssh

I have tried to create a new ssh session with:

$Credential = Get-Credential
$KeyFile = 'C:\Users\mark\Documents\ssh\privkey.ppk'
$sesh = New-SSHSession -ComputerName neon.localdomain -Credential $credential -Keyfile $KeyFile

I put in root and blank password for Get-Credential but I get this error:

New-SSHSession : Invalid private key file.

I tried to convert the privkey file to a string by reading it and converting to base64 encoded but I get the same error:

$privkeyString = Get-Content $KeyFile
$Bytes = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($privkeyString))
$sesh = New-SSHSession -ComputerName neon.localdomain -Credential $credential -KeyString $Bytes

I also tried this but get the same error:

$sesh = New-SSHSession -ComputerName neon.localdomain -Credential $credential -KeyString $privkeystring

Any ideas on how to connect to a linux server using PowerShell with a private key file?

like image 572
Mark Allison Avatar asked Jan 03 '23 10:01

Mark Allison


1 Answers

New-SSHSession doesn't recognize PuTTY's key format (unfortunately neither the Gallery nor the project page mention this, but I found it in a PowerShellMagazine article). You need the private key in the OpenSSH format. You can convert the private key with PuTTYgen:

  1. Click File → Load private key.
  2. Enter the passphrase if the key is password-protected.
  3. Click Conversions → Export OpenSSH key.
  4. Enter the filename for the exported key (do NOT overwrite the PPK file) and click Save.
  5. Exit PuTTYgen.

Run New-SSHSession with the new key file:

$computer = 'neon.localdomain'
$username = 'foo'
$keyfile  = 'C:\path\to\priv_openssh.key'

$sess = New-SSHSession -Computer $computer -Credential $username -Keyfile $keyfile
like image 157
Ansgar Wiechers Avatar answered Jan 13 '23 15:01

Ansgar Wiechers