The new Windows terminal was released back in June of 2019 and has brought several exciting and modern features such as support for tabs, availability for in-depth styling, as well as a configurable JSON file to the Windows Command Line environment. These components together offer the terminal user an endless array of configurations, making this a valuable tool for development work and system administration. It also lends itself to creativity and finding the best fit for the type of work you find yourself doing at the command line.
If you do not already have the new Windows Terminal installed, this article from Microsoft will get you up and running.
Expanded Profile Support
One of the most exciting features to me is the Windows Terminal’s support for profiles. These profiles make up the different command line environments on your machine and, by default, include Windows Powershell, Command Prompt and the Azure Cloud Shell. If you also have a Windows Subsystem for Linux Distribution installed, that shell will automatically be loaded into one of your Windows Terminal profiles. The nice thing about support for different profiles is that we can create and edit them as we wish. In this tutorial, I’ll be diving into configuring a profile for connecting to SSH servers from the new Windows Terminal. Then I’ll continue on to show you to how to tie this together with SSH Keypairs.
Prerequisites
- Valid SSH User Account and Credentials for the SSH server
- Windows Terminal installed
- OpenSSH enabled on Windows 10
- SSH Server with Public Key Authentication allowed (optional)
To begin, we will start by opening our settings.json file within your favorite text editor and creating a new profile within the profiles list for our SSH connection.
Getting Started
The settings.json file is accessible within Windows Terminal by pressing CTRL + , or by navigating to the drop-down arrow and selecting Settings. Once open, you will see that the profiles array is made up of several different properties. You can find the full list here:
Out of simplicity, I will create my new entry at the bottom of the list and add a comma to the closing brace of the above profile. Use the below code to add a new profile for our SSH connection:
{
"guid": "{5063f744-37f9-4c7c-aba5-51fa0789ee1a}", //Random GUID
"hidden": false, //Show the profile in the dropdown
"name": "server1", //Name of profile
"commandline": "ssh bob@server1" //Program, replace user/host
}
Notes on Properties
Each profile you add will need a unique random guid property. You can choose the name that you would like to show within the drop-down menu with the name property. The commandline property allows the user to supply the name of the executable used when the profile is launched.
Looking at the default options, we can see that the commandline property calls executables like powershell.exe and cmd.exe. Applying this same idea, we can begin to create the profile using the SSH executable then apply some basic SSH concepts to fully automate our login process. Make sure to substitute your username and hostname or IP Address within the profile.
Now what?
At this point, we have a functioning profile that launches the SSH executable and connects to the server with the username provided, but it still requires a password. This works perfectly fine, but wouldn’t it be nice to open this profile with a keyboard shortcut then have the SSH executable utilize an SSH Keypair to provide passwordless authentication to the server?
Setting up the SSH Client for Public Key Authentication
We will begin this process by creating a new SSH keypair to use with this server. You can skip this step if you already have a keypair you utilize for the server you are connecting to.
I will utilize OpenSSH’s built-in functionality for generating private keypairs, ssh-keygen. To do this, I will run ssh-keygen then specify a name for the keypair after being prompted and, finally, provide the key a secure passphrase for added security. You should always set passphrases for your keypairs in case they end up in the wrong hands somehow. For more in-depth information on ssh-keygen’s functionality and security, check out the manual page.
The input will be the following:
ssh-keygen # Generate your new SSH keypair # Give it a name and a passphrase
Here’s an example output:
Moving Your Public Key to the SSH Server
Once we have our keypair created, it will by default appear within your C:\Users\$ENV:USERNAME\.ssh\ folder with the public key appended with .pub and the private key appearing as the name you associated with the keypair. Now, we must move our public key over to the authorized_keys file within your respective /home/.ssh/ directory on the server. There is a multitude of ways to do this, but out of simplicity and the lack of a tool like ssh-copy-id on Windows, we will utilize another piece of OpenSSH’s suite—SCP—to move our file itself to the server. Only move your public key; the private key should never be copied to other machines.
I will move my public key over to my home folder (~) on the SSH server using the following SCP command. You will be prompted to log in with your SSH credentials:
scp C:\Users\$ENV:USERNAME\.ssh\yourpublickey.pub user@ipadddress:~ #Replace user@ipaddress with your user and IP
Now that we have our public key on the server, we can copy and paste it into our authorized_keys file to allow password-less login using this keypair. SSH into the server using your username and password. Next, copy the contents of the public key, and authorize it by adding it to the authorized_keys file within your /home/.ssh/ directory:
#Read out your public key and copy the output
cat yourpublickey.pub
#Open your authorized_keys file in vim
sudo vim ~/.ssh/authorized_keys
#Paste the copied output within the authorized_keys file, right click within vim to paste the contents.
Once you are within vim (or your preferred UNIX text editor), follow these steps:
- Enter insert mode by pressing (i)
- Navigate to a new line if you have additional SSH Keys
- Right-click to paste the contents of the public key
- Press Esc + :wq! to save and exit the file
Note: Feel free to remove your public key from your home directory with the rm command. We will not be using that Public Key any longer since we have configured it as an authorized key already.
Tying It All Together
That is it! We can confirm that password-less login is working by opening our profile we made earlier from the Windows Terminal drop-down menu. Let’s give that a go:
Great! It works! We were prompted for our SSH key passphrase and granted password-less login via our profile we created in the Windows Terminal application. If you manage multiple servers with multiple keypairs, I would recommend looking into creating an SSH configuration file. This configuration file would automatically apply your preconfigured settings to each host you connect to. Learn more about SSH configuration files.
To recap, in this tutorial we covered creating an SSH profile within the new Windows Terminal then configuring this profile for password-less authentication using a private keypair. This setup gives some serious management capability for anyone who works at the terminal on multiple systems concurrently. I hope you found this tutorial helpful in configuring your terminal, and don’t forget to dig into the other cool things the new Windows Terminal has to offer like keyboard shortcuts, color schemes and pane splitting. Check out their full documentation, and feel free to reach out to us at InterWorks if we can help you in your exploration.
Статья больше актуальна для Windows 10, ведь это самая прекрасная операционная система для десктопа.. Но без Linux наш мир не обойдется, поэтому многим людям приходится подключаться по ssh к своим серверам, будь они на отдельном компе или на запущенной виртуальной машине, различное окружение для разработки, атс на Asterisk и просто роутер или файлопомойка, все это обычно на Линуксе, он легкий, гибкий и может быть запущен на любом одноплатнике.
Ни для кого не секрет, что в Windows 10 есть терминал со вкладками и ssh, для этого даже не требуется устанавливать WSL, в простом PowerShell можно набрать ssh user@host и работать по ssh
Для того, чтобы не вводить каждый раз пароль, нам нужно сгенерировать ключ ssh
ssh-keygen
//дальше просто энтер жмем и все
А дальше прокинуть ключ на сервер
cat ~/.ssh/id_rsa.pub | ssh user@192.168.200.100 "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"Но остается один момент, лень вводить имя пользователя для подключения по SSH, если имя локального пользователя отличается от удаленного
Для этого заходим в папку C:\Users\Username\.ssh, в ней открываем или создаем файл config и пишем или дописываем такое
Host 192.168.0.2
HostName 192.168.0.2
User username111
Тепеоб просто можем вводить ssh 192.168.0.2 и заходить на нужный сервер, у меня в локальной сети несколько таких серверов и еще виртуалками развернуто несколько.
I have not used Linux very much since running Ubuntu almost 15 years ago. Now I have some Raspberry Pi and recently converted my virtual machine host to Ubuntu. So I have been using SSH a lot more, and I want to make it easier to SSH into my growing litter of Linux boxes.
This guide is mostly instructions for future me when I inevitably forget them or pave over my machine again.
For the examples, I’ll be using the username user and the machine reliablechair, which is on the network at reliablechair.lan.
Install OpenSSH
OpenSSH is offered as a Windows feature, but I prefer to install it with Chocolatey.
Run the following commands in an elevated PowerShell console.
choco install openssh
cd 'C:\Program Files\OpenSSH-Win64\'
Set-Service -Name ssh-agent -StartupType Automatic
Start-Service ssh-agent
Create an SSH key
The next step is to create an SSH key. I am making one for each target machine, which is probably not necessary. You can use the same key for multiple machines if desired. In that case, you can leave off the filename and use the default name provided by ssh-keygen.
You can choose to use a passphrase to secure the key or not. If you do, you will have to enter the passphrase at some point before SSHing into the machine.
These commands do not need an elevated console.
cd ~
ssh-keygen -t rsa -b 4096 -f .\.ssh\reliablechair
Add an initial entry to SSH config
This entry will let us connect to reliablechair with a password while copy the public key over. Without setting this up, you could get connection errors if SSH tries to use other SSH keys on your machine.
With this entry, using ssh reliablechair will be the same as ssh user@reliablechair.lan.
Host reliablechair
User user
HostName reliablechair.lan
PreferredAuthentications password
Copy the public key to the target machine
This command will copy the public key into the target machine’s authorized keys file.
cat .\.ssh\reliablechair.pub | ssh reliablechair "mkdir -p .ssh && cat >> .ssh/authorized_keys"
Update entry in SSH config
Switch the entry for reliablechair to use the SSH key. Setting AddKeysToAgent to yes will add the key to your ssh-agent session. This means that if you set a passphrase on the key, you won’t have to enter it after the initial session.
Host reliablechair
User user
HostName reliablechair.lan
PreferredAuthentications publickey
IdentitiesOnly yes
IdentityFile c:\Users\Ryan\.ssh\reliablechair
AddKeysToAgent yes
ssh-add
You can also call ssh-add directly.
ssh-add $env:HOME\.ssh\reliablechair
SSH connection profile for Windows Terminal
Open the Windows Terminal settings. Add a new entry under profile > list. Use a new GUID for each entry.
{
"guid": "{474e775e-4f2a-5b96-ac1e-a2962a402335}",
"hidden": false,
"name": "Reliable Chair",
"commandline": "ssh reliablechair"
}
Now there is an option to open a connection to reliablechair in the new tab menu for Windows Terminal.
Wrap-up
With a little configuration, it is easy to create SSH sessions from Windows Terminal.
This post was originally published at blog.rousseau.dev. Cover photo by John Barkiple on Unsplash.
I like to have a linux machine for some lab stuff which I can access from multiple machines prefereably over SSH. Because Windows 10 ships with an integrated SSH client and Windows Terminal looks just awesome I wanted to use Windows Terminal to access my linux machine running on Azure over SSH. Today I’d like to show you my setup.
Generate a Key Pair
|
|
Add SSH config file
C:\Users\%USERNAME%\.ssh\config
|
|
Test the SSH connection
ssh horus
Windows Terminal Configuration
Create a new GUID with Powershell and the command: (New-Guid).Guid
|
|
Sync Windows Terminal Settings with OneDrive
We can setup a symlink to use the Windows Terminal Config stored in OneDrive:
|
|
Howto keep ssh config in sync between machines
To sync the SSH settings we can configure a Junction:
|
|
|
|
Introduction
In the early days of doing server administration on Windows we were mostly using the Putty SSH client, either with a ton of profiles, or within some third
party program like mRemote.
None of these made it simple to export and move your remote hosts config around.
At some point, Microsoft added the GNU SSH client to their official Windows packages, we briefly touched on the
subject in our article about WSL and the new Windows terminal — We’ll be using the latter in our screenshots.
We’ll present what we think is a nice way to neatly organize your server accesses and switch to key pair
authentication for better security.
Installing the SSH client
It just sits in the Windows optional features.
On my test system it was already installed:
The feature installs multiple executables aside from ssh.exe, including scp, the ssh-agent
service and more.
If you had to install it, you may need to restart your user session for it to be immediately available in command
line sessions.
We could already log into our server using something like:
ssh admin@172.20.1.117
Where admin is the administrative user name you were given with the server access information, and
172.20.1.117 here is the local IP address of your server on the Net7 VPN (which is required to be connected).
For other servers on different providers you may have to use a public IP address or domain name.
Even Windows machines could technically be setup to offer SSH sessions but that is out of scope for this article.
The SSH client will ask you to confirm the host public key when connecting for the first time. That key is unique to
that SSH server and is used to make sure you’re connecting to the right server.
The client will cache the key and alert you if a server at the same IP address suddenly presents a different host
key.
Key pair authentication
It’s possible to use pairs of keys instead of passwords to connect to SSH servers.
These key pairs are composed of a public key and a private key which are linked by mathematical
properties but in such a way that it’s extremely hard to derive the private key from the public key.
Which comes in handy because the public key is what you can copy and share around, whereas the private key should be
safely kept only on trusted storage and is usually (will be the case if you follow this article) encrypted by its own
password.
As far as SSH is concerned, servers can have a list of public keys that are allowed to connect.
The SSH client has to demonstrate being the real owner of that public key by performing signatures that are only
doable with
the private key from that specific key pair.
The rest of the SSH session will be encrypted using a negociated session key so that, in case your private key is
compromised, past communications with the server still can’t be decrypted.
In short, your key pair is used to identify or authenticate you very precisely and safely, possibly on multiple
services.
Key pairs (including the encrypted private key — in case it leaks) are much harder to break than password
hashes and thus are considered safer than passwords. We also tend to not write private keys down somewhere.
Generating your key pair
To generate your key pair, open a terminal and run the following command:
ssh-keygen -t ed25519 -C "<YOUR_EMAIL_ADDRESS>"
Where you should fill in your email address. In case you’d want to use the key pair for Github later on,
make sure
you use the email address registered to your Github account (same goes for Gitlab and others).
You will be asked for a passphrase to encrypt the private key with. You should always provide one. A possible
exception to this rule is when you need two servers to access each other and you’re certain of the security of the
whole thing.
Having an encrypted system and user volume and adequate session security (auto-locking etc.) could also justify not
using a passphrase in some cases.
You should never move your private key around over the Internet and strive to be extremely safe when doing so. An
encrypted private key adds an extra layer of security in case your private key does leak around somewhere.
In case you need to connect to older servers, you might need a RSA key pair, which is an older algorithm (it’s
still safe provided you use large key sizes):
ssh-keygen -t rsa -b 4096 -C "<YOUR_EMAIL_ADDRESS>"
You should now have a .ssh directory in your user directory (C:\Users\<YOUR_NAME>) with the following
files:
- id_ed25519 — This is your private key; On Linux systems it shouldn’t be visible to other users
(should have been created with the right permissions) - id_ed25519.pub — This is your public key. You can copy it around safely; When you need to provide a
key to any service or copy a key to any server, it’s always the public key
Creating the config file (list of SSH hosts)
Open a command line and make sure your current directory is your user directory (c:\Users\<YOUR_USER>).
You need to create a new file in .ssh called config.
Here’s how to do it with notepad but any editor should do:
notepad .ssh\config
In case the file doesn’t exist, notepad should ask you if you want to create it.
You can now add your SSH hosts in there following a specific format:
Host <HOST_FRIENDLY_NAME>
HostName <IP_ADDRESS_OR_DOMAIN_NAME>
User <REMOTE_USERNAME>
Let’s say our server is called triceratops and sits on VPN IP address 192.168.77.117, and your
user on the server is just admin, this is the entry we’d use:
Host triceratops
HostName 192.168.77.117
User admin
As depicted here in notepad:
We’re free to add more of these Host sections for any SSH host you’d want to connect to.
There are a lot more options you can set per host in the config file. Most of them described here.
We won’t list them here per se but that would be how you set a host to be
on a port that isn’t 22, force using a different key pair, command to run on server upon connection (could be
tmux), …
With your config file in place, you should be able to use the host friendly name (triceratops in our
example) ssh and scp commands. Connecting to the server is now as simple as:
ssh triceratops
Which will ask you for your password because our server hasn’t been configured to allow our key pair yet:
The config file is portable to any system that uses the classic SSH client and can be brought over to Linux,
Mac, and Windows. It shouldn’t contain any secret except for revealing IP address information for your services.
Authorizing our keys on the server
To log into a SSH server as a specific user, your public key has to be present in a special file in the «.ssh»
directory your remote user — which has to be in their home directory, e.g.:
/home/<YOUR_USER>/.ssh/authorized_keys
The .ssh directory might not exist if you have never used the SSH client on that server.
We devised some
command line magic to create the directory when it’s not present and put your public key in authorized_keys
(will append your key to the file in case you already have other keys in there).
The following command assumes your session current directory is your Windows user directory
(c:\Users\<YOUR_USER>).
ssh triceratops "mkdir -p ~/.ssh; tee -a ~/.ssh/authorized_keys" < .ssh\id_ed25519.pub
Make sure you’re referencing the .pub file and NOT the private key.
When we try to connect to triceratops afterwards, it’s still asking for a password, but looking more closely,
that’s not the server password, it’s they private key passphrase.
In practice it looks like nothing has changed but that’s not true, not only can you reuse your key pair for all of
your servers and many services (including Github) and thus use a single master password to access all of these but we
also benefit from the increased security of the key pair authentication scheme.
Optional: Store the private key in the Windows session
It’s possible to make it so that you don’t have to enter your private key passphrase to use the key pair.
We need a Windows service called the «OpenSSH Authentication Service» or sometimes shortened as «ssh-agent». It
should be disabled by default.
To open the Services console, you can press the Windows Key + R and then type services.msc, press enter
to open the services console.
Look for the «OpenSSH Authentication Service» in the list, right click and open properties.
From there, set «Startup type» to automatic if you want that service to start with Windows from now on, and then
start the service (use the «Start» button or right click the service and use start from here).
On some Windows installations, you may have to manually run the services console as administrator or it may not allow
you to start the service.
You can now add your private key to the agent using a command prompt:
ssh-add .ssh\id_ed25519
You should now be able to use the key pair with no password prompt.
Ideally you’d want to manually delete the private key, as it’s now stored in the SSH Agent service and encrypted in
such a way that you can’t get it back.
This is both good and bad as it means moving your private key to another computer is now impossible — You’d
have to create a new key pair. As such it’s not
a bad idea to backup your private key, maybe by storing it on a special USB stick (some USB sticks are even meant to
store
sensitive data).
To delete your private key from the command prompt, when inside of your user directory, you can use:
del .ssh\id_ed25519
Keep in mind that you should now be extra careful with open sessions on your Windows machines, because anyone with
access to
your computer and keyboard could connect to your servers with no password when a session is open.
We suggest having a strong Windows password and locking your screen automatically after a few minutes. You can also
lock it manually using Windows Key + L.
Copying files with scp
You can also use your keypair and config file to easily copy files to your servers using the scp command.
NB: scp uses a «normal» SSH session for file copy and is different from SFTP, even though
the OpenSSH Server can do both of
these.
Copying a single file to remote directory /var/www/html:
scp some_file.html triceratops:/var/www/html/
Copying a directory to your home folder:
scp -r my_project triceratops:/home/admin/
You can also use scp to bring files from the server over to your client machine. For instance, to bring a log
file back to the current directory on your client machine:
scp triceratops:/var/log/auth.log .
