Automating the SSH procedure

In the preceding example, typing the password every single time was necessary. Next, we will use rsa-keygen to auto log into your server. The idea is that we will create a unique key. Then, we will transfer it to the server, and every time we connect to the server via ssh, we will provide our key automatically, which will obviously match. This way we can connect without passwords and it is more secure. So, let's go step by step and see how we can automate this procedure:

  1. Open up your terminal on the client side.
  2. The first step is to create the key pair in the client. You can do this by typing the following command in the terminal:
    ssh-keygen -t rsa  
  • Next, you will need to insert a file name. As seen next, you can type whatever you want here as the filename of your rsa key:
  1. The next step is to create a password. You can leave it blank, and just hit Enter. After this, hit Enter again. You should see something similar to the following, where the rsa keygen is created:
  1. Without closing the terminal or changing the current directory, you can find the files created by simply executing the ls command. In the preceding example, where we define the rsa key name as myrsa, there are two files generated. The first one is called myrsa, and the second one is called myrsa.pub. At this point, it is very important to understand that the file called myrsa (without the pub extension) is your PRIVATE key and is ONLY for you. You must never publish or send it over to anyone. It is just like your secret password.
  2. Now, you need to transfer the myrsa.pub file to the remote host. More precisely, you need to place it in the ~/.ssh/ folder of the remote server.
  3. The final step is to create (if it doesn't exist) the ~/.ssh/authorized_keys file, and copy whatever the myrsa.pub file contains to the authorized_keys file.

Now, you should be ready to log in without a password.

You can finally automate the ssh command with the following simple script file. Replace the IP address of the script with your own Raspberry Pi IP address:

    #!/bin/bash
    # This script opens an ssh connection with the Raspberry Pi
    ssh [email protected]
  

Save this script with the name cpi and place it in /bin in your Linux local machine. Now, the way that I love connecting with my Raspberry Pi Zero W is to simply press Ctrl + Alt + T to open up a Terminal and then, type cpi and hit Enter. Within three seconds, you are connected to the Raspberry Pi.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.190.217.134