How to Set Up SSH Keys on Ubuntu 20.04
Introduction
SSH, or secure shell, is an encrypted protocol used to administer and communicate with servers. When working with an Ubuntu server, chances are you will spend most of your time in a terminal session connected to your server through SSH.
In this guide, we’ll focus on setting up SSH keys for an Ubuntu 20.04 installation. SSH keys provide a secure way of logging into your server and are recommended for all users.
Step 1 — Creating the Key Pair
The first step is to create a key pair on the client machine (usually your computer):
By default recent versions of ssh-keygen
will create a 3072-bit RSA key pair, which is secure enough for most use cases (you may optionally pass in the -b 4096
flag to create a larger 4096-bit key).
After entering the command, you should see the following output:
OutputGenerating public/private rsa key pair.
Enter file in which to save the key (/your_home/.ssh/id_rsa):
Press enter to save the key pair into the .ssh/
subdirectory in your home directory, or specify an alternate path.
If you had previously generated an SSH key pair, you may see the following prompt:
Output/home/your_home/.ssh/id_rsa already exists.
Overwrite (y/n)?
If you choose to overwrite the key on disk, you will not be able to authenticate using the previous key anymore. Be very careful when selecting yes, as this is a destructive process that cannot be reversed.
You should then see the following prompt:
OutputEnter passphrase (empty for no passphrase):
Here you optionally may enter a secure passphrase, which is highly recommended. A passphrase adds an additional layer of security to prevent unauthorized users from logging in. To learn more about security, consult our tutorial on How To Configure SSH Key-Based Authentication on a Linux Server.
You should then see the output similar to the following:
OutputYour identification has been saved in /your_home/.ssh/id_rsa
Your public key has been saved in /your_home/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:/hk7MJ5n5aiqdfTVUZr+2Qt+qCiS7BIm5Iv0dxrc3ks user@host
The key's randomart image is:
+---[RSA 3072]----+
| .|
| + |
| + |
| . o . |
|o S . o |
| + o. .oo. .. .o|
|o = oooooEo+ ...o|
|.. o *o+=.*+o....|
| =+=ooB=o.... |
+----[SHA256]-----+
You now have a public and private key that you can use to authenticate. The next step is to place the public key on your server so that you can use SSH-key-based authentication to log in.
Step 2 — Copying the Public Key to Your Ubuntu Server
The quickest way to copy your public key to the Ubuntu host is to use a utility called ssh-copy-id
. Due to its simplicity, this method is highly recommended if available. If you do not have ssh-copy-id
available to you on your client machine, you may use one of the two alternate methods provided in this section (copying via password-based SSH, or manually copying the key).
Copying the Public Key Using ssh-copy-id
The ssh-copy-id
tool is included by default in many operating systems, so you may have it available on your local system. For this method to work, you must already have password-based SSH access to your server.
To use the utility, you specify the remote host that you would like to connect to, and the user account that you have password-based SSH access to. This is the account to which your public SSH key will be copied.
The syntax is:
You may see the following message:
OutputThe authenticity of host '203.0.113.1 (203.0.113.1)' can't be established.
ECDSA key fingerprint is fd:fd:d4:f9:77:fe:73:84:e1:55:00:ad:d6:6d:22:fe.
Are you sure you want to continue connecting (yes/no)? yes
This means that your local computer does not recognize the remote host. This will happen the first time you connect to a new host. Type “yes” and press ENTER
to continue.
Next, the utility will scan your local account for the id_rsa.pub
key that we created earlier. When it finds the key, it will prompt you for the password of the remote user’s account:
Output/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
username@203.0.113.1's password:
Type in the password (your typing will not be displayed, for security purposes) and press ENTER
. The utility will connect to the account on the remote host using the password you provided. It will then copy the contents of your ~/.ssh/id_rsa.pub
key into a file in the remote account’s home ~/.ssh
directory called authorized_keys
.
You should see the following output:
OutputNumber of key(s) added: 1
Now try logging into the machine, with: "ssh 'username@203.0.113.1'"
and check to make sure that only the key(s) you wanted were added.
At this point, your id_rsa.pub
key has been uploaded to the remote account. You can continue on to Step 3.
Copying the Public Key Using SSH
If you do not have ssh-copy-id
available, but you have password-based SSH access to an account on your server, you can upload your keys using a conventional SSH method.
We can do this by using the cat
command to read the contents of the public SSH key on our local computer and piping that through an SSH connection to the remote server.
On the other side, we can make sure that the ~/.ssh
directory exists and has the correct permissions under the account we’re using.
We can then output the content we piped over into a file called authorized_keys
within this directory. We’ll use the >>
redirect symbol to append the content instead of overwriting it. This will let us add keys without destroying previously added keys.
The full command looks like this:
You may see the following message:
OutputThe authenticity of host '203.0.113.1 (203.0.113.1)' can't be established.
ECDSA key fingerprint is fd:fd:d4:f9:77:fe:73:84:e1:55:00:ad:d6:6d:22:fe.
Are you sure you want to continue connecting (yes/no)? yes
This means that your local computer does not recognize the remote host. This will happen the first time you connect to a new host. Type yes
and press ENTER
to continue.
Afterwards, you should be prompted to enter the remote user account password:
Outputusername@203.0.113.1's password:
After entering your password, the content of your id_rsa.pub
key will be copied to the end of the authorized_keys
file of the remote user’s account. Continue on to Step 3 if this was successful.
Copying the Public Key Manually
If you do not have password-based SSH access to your server available, you will have to complete the above process manually.
We will manually append the content of your id_rsa.pub
file to the ~/.ssh/authorized_keys
file on your remote machine.
To display the content of your id_rsa.pub
key, type this into your local computer:
You will see the key’s content, which should look something like this:
Outputssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCqql6MzstZYh1TmWWv11q5O3pISj2ZFl9HgH1JLknLLx44+tXfJ7mIrKNxOOwxIxvcBF8PXSYvobFYEZjGIVCEAjrUzLiIxbyCoxVyle7Q+bqgZ8SeeM8wzytsY+dVGcBxF6N4JS+zVk5eMcV385gG3Y6ON3EG112n6d+SMXY0OEBIcO6x+PnUSGHrSgpBgX7Ks1r7xqFa7heJLLt2wWwkARptX7udSq05paBhcpB0pHtA1Rfz3K2B+ZVIpSDfki9UVKzT8JUmwW6NNzSgxUfQHGwnW7kj4jp4AT0VZk3ADw497M2G/12N0PPB5CnhHf7ovgy6nL1ikrygTKRFmNZISvAcywB9GVqNAVE+ZHDSCuURNsAInVzgYo9xgJDW8wUw2o8U77+xiFxgI5QSZX3Iq7YLMgeksaO4rBJEa54k8m5wEiEE1nUhLuJ0X/vh2xPff6SQ1BL/zkOhvJCACK6Vb15mDOeCSq54Cr7kvS46itMosi/uS66+PujOO+xt/2FWYepz6ZlN70bRly57Q06J+ZJoc9FfBCbCyYH7U/ASsmY095ywPsBo1XQ9PqhnN1/YOorJ068foQDNVpm146mUpILVxmq41Cj55YKHEazXGsdBIbXWhcrRf4G2fJLRcGUr9q8/lERo9oxRm5JFX6TCmj6kmiFqv+Ow9gI0x8GvaQ== demo@test
Access your remote host using whichever method you have available.
Once you have access to your account on the remote server, you should make sure the ~/.ssh
directory exists. This command will create the directory if necessary, or do nothing if it already exists:
Now, you can create or modify the authorized_keys
file within this directory. You can add the contents of your id_rsa.pub
file to the end of the authorized_keys
file, creating it if necessary, using this command:
In the above command, substitute the public_key_string
with the output from the cat ~/.ssh/id_rsa.pub
command that you executed on your local system. It should start with ssh-rsa AAAA...
.
Finally, we’ll ensure that the ~/.ssh
directory and authorized_keys
file have the appropriate permissions set:
This recursively removes all “group” and “other” permissions for the ~/.ssh/
directory.
If you’re using the root account to set up keys for a user account, it’s also important that the ~/.ssh
directory belongs to the user and not to root:
In this tutorial our user is named sammy but you should substitute the appropriate username into the above command.
We can now attempt passwordless authentication with our Ubuntu server.
Step 3 — Authenticating to Your Ubuntu Server Using SSH Keys
If you have successfully completed one of the procedures above, you should be able to log into the remote host without providing the remote account’s password.
The basic process is the same:
If this is your first time connecting to this host (if you used the last method above), you may see something like this:
OutputThe authenticity of host '203.0.113.1 (203.0.113.1)' can't be established.
ECDSA key fingerprint is fd:fd:d4:f9:77:fe:73:84:e1:55:00:ad:d6:6d:22:fe.
Are you sure you want to continue connecting (yes/no)? yes
This means that your local computer does not recognize the remote host. Type “yes” and then press ENTER
to continue.
If you did not supply a passphrase for your private key, you will be logged in immediately. If you supplied a passphrase for the private key when you created the key, you will be prompted to enter it now (note that your keystrokes will not display in the terminal session for security). After authenticating, a new shell session should open for you with the configured account on the Ubuntu server.
If key-based authentication was successful, continue on to learn how to further secure your system by disabling password authentication.
Step 4 — Disabling Password Authentication on Your Server
If you were able to log into your account using SSH without a password, you have successfully configured SSH-key-based authentication to your account. However, your password-based authentication mechanism is still active, meaning that your server is still exposed to brute-force attacks.
Before completing the steps in this section, make sure that you either have SSH-key-based authentication configured for the root account on this server, or preferably, that you have SSH-key-based authentication configured for a non-root account on this server with sudo
privileges. This step will lock down password-based logins, so ensuring that you will still be able to get administrative access is crucial.
Once you’ve confirmed that your remote account has administrative privileges, log into your remote server with SSH keys, either as root or with an account with sudo
privileges. Then, open up the SSH daemon’s configuration file:
Inside the file, search for a directive called PasswordAuthentication
. This line may be commented out with a #
at the beginning of the line. Uncomment the line by removing the #
, and set the value to no
. This will disable your ability to log in via SSH using account passwords:
. . .
PasswordAuthentication no
. . .
Save and close the file when you are finished by pressing CTRL+X
, then Y
to confirm saving the file, and finally ENTER
to exit nano. To actually activate these changes, we need to restart the sshd
service:
As a precaution, open up a new terminal window and test that the SSH service is functioning correctly before closing your current session:
Once you have verified your SSH service is functioning properly, you can safely close all current server sessions.
The SSH daemon on your Ubuntu server now only responds to SSH-key-based authentication. Password-based logins have been disabled.
Conclusion
You should now have SSH-key-based authentication configured on your server, allowing you to sign in without providing an account password.
Related Post
Top Five Free Ai Content Generator: Free Ai Content Generator 2023
The soul of a website is called the content. So it is easy to understand that the website has no value without content. And writing content takes a lot of research. There is a lot to think about. Whether it is WordPress or Blogspot, everyone knows how hard it is to write content. But what if these contents become automatically generated? Yes, you are right, today I will talk about something like this in this article. Today I will share with you five free AI content generators that are completely free.What Is Ai Generated Content?Before knowing what AI content is, we need to know what AI is. AI is Artificial Intelligence. Many people have more or fewer ideas about artificial intelligence. But for those who don't know. Artificial intelligence is when a machine such as a computer can make decisions by itself, it is called artificial intelligence. Now let me tell you what AI content is. AI content means you just give a few hints and it will automatically write the entire content within seconds. This content is called AI-generated content.Is Ai Generated Content Unique?Yes, Of course. Because these AI-generated contents are generated by different AI content generators completely by themselves. So it will give you completely unique content. AI content generators will write the content based on the topic which are you give.How Does Ai Content Generator Work?The way Ai content generators work is that You first give the generator little hints about the topic you want to write about like it might ask you for a headline. Give some keywords in the topic and it will generate unique content for you in a few seconds.Best Free Ai Content Generator ToolsThere are many AI generator tools. But today I will talk about 5 content generators that are better than other content generators and easy to use. And these content generators will give you much better content than any other content generator.Simplified- Content Generator ToolSimplified is one of the best content generator tools. There are a lot of free tools you'll find here. You can generate up to five thousand words by Simplified which is huge. And also there are a lot of free features available in Simplified.1. Ryter: An All In One Content WriterRyter is a next-level content generator tool Because it can understand the language model deeply. For this reason, it can generate the best content. You can use all the features for free but you can only generate 5000 words per month.2. Copy Ai Free Ai Content GeneratorCopy AI is the best content generator of any other tool. Because it is built on the world's best ai technology. So it can generate more creative and best content very fast. You can generate 100 pieces of content in the first months by Copy Ai Free Content Generator.3. Content Bot Advance AI WriterContent Bot Advance AI Writer tool can generate content from any short hints or keywords. And it's a very powerful content generator tool. You can generate 500 pieces of content per month and one thousand five hundred long-form editor words every month. But it's a little bit hard to use.4. Smart Copy By UnbounceSmart Copy is one of the advanced level AI writing tools. You can use it to generate your content You can use all features fully free but you can generate only 5 articles per day.So here is the top five best AI content generator tool you can use a lot of free features without purchasing it but there is a few limitations. So try to use free features.
Read MoreHow to Use Ansible to Install and Set Up Docker on Ubuntu 22.04
IntroductionServer automation now plays an essential role in systems administration, due to the disposable nature of modern application environments. Configuration management tools such as Ansible are typically used to streamline the process of automating server setup by establishing standard procedures for new servers while also reducing human error associated with manual setups.Ansible offers a simple architecture that doesn’t require special software to be installed on nodes. It also provides a robust set of features and built-in modules which facilitate writing automation scripts.This guide explains how to use Ansible to automate the steps contained in our guide on How To Install and Use Docker on Ubuntu 22.04. Docker is an application that simplifies the process of managing containers, resource-isolated processes that behave in a similar way to virtual machines, but are more portable, more resource-friendly, and depend more heavily on the host operating system.PrerequisitesIn order to execute the automated setup provided by the playbook in this guide, you’ll need:One Ansible control node: an Ubuntu 22.04 machine with Ansible installed and configured to connect to your Ansible hosts using SSH keys. Make sure the control node has a regular user with sudo permissions and a firewall enabled, as explained in our Initial Server Setup guide. To set up Ansible, please follow our guide on How to Install and Configure Ansible on Ubuntu 22.04.One or more Ansible Hosts: one or more remote Ubuntu 22.04 servers previously set up following the guide on How to Use Ansible to Automate Initial Server Setup on Ubuntu 22.04.Before proceeding, you first need to make sure your Ansible control node is able to connect and execute commands on your Ansible host(s). For a connection test, check Step 3 of How to Install and Configure Ansible on Ubuntu 22.04.What Does this Playbook Do?This Ansible playbook provides an alternative to manually running through the procedure outlined in our guide on How To Install and Use Docker on Ubuntu 22.04. Set up your playbook once, and use it for every installation after.Running this playbook will perform the following actions on your Ansible hosts:Install aptitude, which is preferred by Ansible as an alternative to the apt package manager.Install the required system packages.Install the Docker GPG APT key.Add the official Docker repository to the apt sources.Install Docker.Install the Python Docker module via pip.Pull the default image specified by default_container_image from Docker Hub.Create the number of containers defined by the container_count variable, each using the image defined by default_container_image, and execute the command defined in default_container_command in each new container.Once the playbook has finished running, you will have a number of containers created based on the options you defined within your configuration variables.To begin, log into a sudo enabled user on your Ansible control node server.Step 1 — Preparing your PlaybookThe playbook.yml file is where all your tasks are defined. A task is the smallest unit of action you can automate using an Ansible playbook. But first, create your playbook file using your preferred text editor:nano playbook.yml CopyThis will open an empty YAML file. Before diving into adding tasks to your playbook, start by adding the following:playbook.yml--- - hosts: all become: true vars: container_count: 4 default_container_name: docker default_container_image: ubuntu default_container_command: sleep 1 CopyAlmost every playbook you come across will begin with declarations similar to this. hosts declares which servers the Ansible control node will target with this playbook. become states whether all commands will be done with escalated root privileges.vars allows you to store data in variables. If you decide to change these in the future, you will only have to edit these single lines in your file. Here’s a brief explanation of each variable:container_count: The number of containers to create.default_container_name: Default container name.default_container_image: Default Docker image to be used when creating containers.default_container_command: Default command to run on new containers.Note: If you want to see the playbook file in its final finished state, jump to Step 5. YAML files can be particular with their indentation structure, so you may want to double-check your playbook once you’ve added all your tasks.Step 2 — Adding Packages Installation Tasks to your PlaybookBy default, tasks are executed synchronously by Ansible in order from top to bottom in your playbook. This means task ordering is important, and you can safely assume one task will finish executing before the next task begins.All tasks in this playbook can stand alone and be re-used in your other playbooks.Add your first tasks of installing aptitude, a tool for interfacing with the Linux package manager, and installing the required system packages. Ansible will ensure these packages are always installed on your server:playbook.yml tasks: - name: Install aptitude apt: name: aptitude state: latest update_cache: true - name: Install required system packages apt: pkg: - apt-transport-https - ca-certificates - curl - software-properties-common - python3-pip - virtualenv - python3-setuptools state: latest update_cache: true CopyHere, you’re using the apt Ansible built-in module to direct Ansible to install your packages. Modules in Ansible are shortcuts to execute operations that you would otherwise have to run as raw bash commands. Ansible safely falls back onto apt for installing packages if aptitude is not available, but Ansible has historically preferred aptitude.You can add or remove packages to your liking. This will ensure all packages are not only present, but on the latest version, and do after an update with apt is called.Step 3 — Adding Docker Installation Tasks to your PlaybookYour task will install the latest version of Docker from the official repository. The Docker GPG key is added to verify the download, the official repository is added as a new package source, and Docker will be installed. Additionally, the Docker module for Python will be installed as well:playbook.yml - name: Add Docker GPG apt Key apt_key: url: https://download.docker.com/linux/ubuntu/gpg state: present - name: Add Docker Repository apt_repository: repo: deb https://download.docker.com/linux/ubuntu jammy stable state: present - name: Update apt and install docker-ce apt: name: docker-ce state: latest update_cache: true - name: Install Docker Module for Python pip: name: docker CopyYou’ll see that apt_key and apt_repository built-in Ansible modules are first pointed at the correct URLs, then tasked to ensure they are present. This allows installation of the latest version of Docker, along with using pip to install of the module for Python.Step 4 — Adding Docker Image and Container Tasks to your PlaybookThe actual creation of your Docker containers starts here with the pulling of your desired Docker image. By default, these images come from the official Docker Hub. Using this image, containers will be created according to the specifications laid out by the variables declared at the top of your playbook:playbook.yml - name: Pull default Docker image community.docker.docker_image: name: "{{ default_container_image }}" source: pull - name: Create default containers community.docker.docker_container: name: "{{ default_container_name }}{{ item }}" image: "{{ default_container_image }}" command: "{{ default_container_command }}" state: present with_sequence: count={{ container_count }} Copydocker_image is used to pull the Docker image you want to use as the base for your containers. docker_container allows you to specify the specifics of the containers you create, along with the command you want to pass them.with_sequence is the Ansible way of creating a loop, and in this case, it will loop the creation of your containers according to the count you specified. This is a basic count loop, so the item variable here provides a number representing the current loop iteration. This number is used here to name your containers.Step 5 — Reviewing your Complete PlaybookYour playbook should look roughly like the following, with minor differences depending on your customizations:playbook.yml--- - hosts: all become: true vars: container_count: 4 default_container_name: docker default_container_image: ubuntu default_container_command: sleep 1d tasks: - name: Install aptitude apt: name: aptitude state: latest update_cache: true - name: Install required system packages apt: pkg: - apt-transport-https - ca-certificates - curl - software-properties-common - python3-pip - virtualenv - python3-setuptools state: latest update_cache: true - name: Add Docker GPG apt Key apt_key: url: https://download.docker.com/linux/ubuntu/gpg state: present - name: Add Docker Repository apt_repository: repo: deb https://download.docker.com/linux/ubuntu jammy stable state: present - name: Update apt and install docker-ce apt: name: docker-ce state: latest update_cache: true - name: Install Docker Module for Python pip: name: docker - name: Pull default Docker image community.docker.docker_image: name: "{{ default_container_image }}" source: pull - name: Create default containers community.docker.docker_container: name: "{{ default_container_name }}{{ item }}" image: "{{ default_container_image }}" command: "{{ default_container_command }}" state: present with_sequence: count={{ container_count }} CopyFeel free to modify this playbook to best suit your individual needs within your own workflow. For example, you could use the docker_image module to push images to Docker Hub or the docker_container module to set up container networks.Note: This is a gentle reminder to be mindful of your indentations. If you run into an error, this is very likely the culprit. YAML suggests using 2 spaces as an indent, as was done in this example.Once you’re satisfied with your playbook, you can exit your text editor and save.Step 6 — Running your PlaybookYou’re now ready to run this playbook on one or more servers. Most playbooks are configured to be executed on every server in your inventory by default, but you’ll specify your server this time.To execute the playbook only on server1, connecting as sammy, you can use the following command:ansible-playbook playbook.yml -l server1 -u sammy CopyThe -l flag specifies your server and the -u flag specifies which user to log into on the remote server. You will get output similar to this:Output. . . changed: [server1] TASK [Create default containers] ***************************************************************************************************************** changed: [server1] => (item=1) changed: [server1] => (item=2) changed: [server1] => (item=3) changed: [server1] => (item=4) PLAY RECAP *************************************************************************************************************************************** server1 : ok=9 changed=8 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 Note: For more information on how to run Ansible playbooks, check our Ansible Cheat Sheet Guide.This indicates your server setup is complete! Your output doesn’t have to be exactly the same, but it is important that you have zero failures.When the playbook is finished running, log in via SSH to the server provisioned by Ansible to check if the containers were successfully created.Log in to the remote server with:ssh sammy@your_remote_server_ip CopyAnd list your Docker containers on the remote server:sudo docker ps -a CopyYou should see output similar to this:OutputCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES a3fe9bfb89cf ubuntu "sleep 1d" 5 minutes ago Created docker4 8799c16cde1e ubuntu "sleep 1d" 5 minutes ago Created docker3 ad0c2123b183 ubuntu "sleep 1d" 5 minutes ago Created docker2 b9350916ffd8 ubuntu "sleep 1d" 5 minutes ago Created docker1 This means the containers defined in the playbook were created successfully. Since this was the last task in the playbook, it also confirms that the playbook was fully executed on this server.ConclusionAutomating your infrastructure setup can not only save you time, but it also helps to ensure that your servers will follow a standard configuration that can be customized to your needs. With the distributed nature of modern applications and the need for consistency between different staging environments, automation like this has become a central component in many teams’ development processes.In this guide, you demonstrated how to use Ansible to automate the process of installing and setting up Docker on a remote server. Because each individual typically has different needs when working with containers, we encourage you to check out the official Ansible documentation for more information and use cases of the docker_container Ansible module.If you’d like to include other tasks in this playbook to further customize your initial server setup, please refer to our introductory Ansible guide Configuration Management 101: Writing Ansible Playbooks.
Read More