I have uses the Dotnet Core Nuget package SSH.NET to SSH into machines a few times, is a very simple, slick and handy tool to have. However, you cannot SSH into a Virtual Machine(VM) in Hyper-V that easy without some extra fiddling to get an exposed IP Address.
With your standard SSH command you can run the simple:
This can have many other attributes, but lets keep it simple.
If your VM has an IP Address assigned to the Network Adapter then this can still be very simple, with using the user for the machine and the IP Address as the host.
However, not every VM in some situation will have an IP Address and therefore you cannot connect to it like this.
You can though if you use the Hyper-V Console CLI(HVC). If installed it can be located in ‘
C:\Windows\System32\hvc.exe‘ and it is normally install when enabling the Hyper-V Feature in Windows. This tool enables your to communicate to your VM via the Hyper-V Bus in-between your local machine and the VM.
To use this tool you can run the same SSH command but with the HVC prefix:
hvc ssh User@Host
However, instead of the host you can pass the Hyper-V VM name, which you can get from the Hyper-V Program or with PowerShell in Administrator mode:
This is great to use in the Terminal, but doesn’t let you use standard SSH commands, which the SSH.Net tool uses. I have not come across a tool to do this execution via Dotnet Core yet, so I have come up with this solution.
What we can do to accomplish this is port forwarding, where we tell the VM to route traffic from one port on the VM to another port on the local machine.
Below we are telling the VM to push port 22 traffic, which is the SSH standard port, to port 2222 on the local machine with the correct Username and VM Name.
hvc.exe ssh -L 2222:Localhost:22 User@VmName
Once this has been done you can then run the standard SSH command, but with the port parameter and ‘Localhost’ as the Host, the same as you SSH to your own local machine.
Ssh user@Localhost -p 2222
To get this working in C# I would recommend using SSH keys to avoid the requirement of passwords as you would need key entry for that, and then the PowerShell Nuget package to run the HVC command like below:
$SystemDirectory = [Environment]::SystemDirectory cd $SystemDirectory hvc.exe ssh -L 2222:Localhost:22 User@VmName -i "KeyPath" -FN