How To Set Up SSH Keys

About SSH Keys

SSH keys provide a more secure way of logging into a virtual private server with SSH than using a password alone. While a password can eventually be cracked with a brute force attack, SSH keys are nearly impossible to decipher by brute force alone. Generating a key pair provides you with two long string of characters: a public and a private key. You can place the public key on any server, and then unlock it by connecting to it with a client that already has the private key. When the two match up, the system unlocks without the need for a password. You can increase security even more by protecting the private key with a passphrase.
Step One—Create the RSA Key Pair
The first step is to create the key pair on the client machine (there is a good chance that this will just be your computer): $ ssh-keygen -t rsa
Step Two—Store the Keys and Passphrase
Once you have entered the Gen Key command, you will get a few more questions: Enter file in which to save the key (/home/demo/.ssh/id_rsa): You can press enter here, saving the file to the user home (in this case, my example user is called demo). Enter passphrase (empty for no passphrase): It's up to you whether you want to use a passphrase. Entering a passphrase does have its benefits: the security of a key, no matter how encrypted, still depends on the fact that it is not visible to anyone else. Should a passphrase-protected private key fall into an unauthorized user’s possession, they will be unable to log in to its associated accounts until they figure out the passphrase, buying the hacked user some extra time. The only downside, of course, to having a passphrase, is then having to type it in each time you use the Key Pair.
The entire key generation process looks like this:

$ ssh-keygen -t rsa

Generating public/private rsa key pair.
Enter file in which to save the key (/home/demo/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/demo/.ssh/id_rsa.
Your public key has been saved in /home/demo/.ssh/id_rsa.pub.
The key fingerprint is:
4a:dd:0a:c6:35:4e:3f:ed:27:38:8c:74:44:4d:93:67 demo@a
The key's randomart image is:
+-- [ RSA 2048]-- -- +
| .oo. |
| . o.E |
| + . o |
| . = = . |
| = S = . |
| o + = + |
| . o + o . |
| . o |
| |
+-- -- -- -- -- -- -- -- -+

The public key is now located in /home/demo/.ssh/id_rsa.pub The private key (identification) is now located in /home/demo/.ssh/id_rsa
Step Three—Copy the Public Key
The above process is also called a Code Delivery Pipeline.
Once the key pair is generated, it's time to place the public key on the virtual server that we want to use. You can copy the public key into the new machine's authorized keys file with the ssh-copy- id command. Make sure to replace the example username and IP address below.

$ ssh-copy- id user@192.168.2.5

Alternatively, you can paste in the keys using SSH:
$ cat ~/.ssh/id_rsa.pub | ssh user@192.168.2.5 "mkdir -p ~/.ssh &&cat >>~/.ssh/authorized_keys"

No matter which command you chose, you should see something like:
The authenticity of host '192.168.2.5 (192.168.2.5)'can't be established.RSA key
fingerprint is b1:2d:33:67:ce:35:4d:5f:f3:a8:cd:c0:c4:48:86:12. Are you sure you want to continue connecting (yes/no)? Yes Warning: Permanently added '12.34.56.78'(RSA) to the list of known hosts. user@12.34.56.78's password: Now try logging into the machine, with "ssh 'user@12.34.56.78'", and check in: ~/.ssh/authorized_keys
to make sure we haven't added extra keys that you weren't expecting. Now you can go ahead and log into user@192.168.2.5 and you will not be prompted for a password. However, if you set a passphrase, you will be asked to enter the passphrase at that time (and whenever else you log in in the future).

Exercise:
-Create 4 centos vm’s. One among these four vm one will be the automation box from where we will run our scripts.
-Do SSH key exchange from automation box to rest of the three vm’s.
Write a script which will install Apache & mysql server, start and enable both services and check status of apache, mysql & iptables. Execute this script from automation box for all three vm and validate.
Few Sample scripts
A script to automate below mentioned task on Centos
Install mlocate search tool, update mlocate database
Install, start & enable httpd service.
Find files with permission 0777 and delete it.
Check hard disk free space and alerts if its running low on disk space.

#!/bin/bash
# Sample script to automate tasks:
# -Update local file database:
echo -e "\e[4;32mInstalling mlocate\e[0m"
sudo yum install mlocate -y
echo ""
echo -e "\e[4;32mUPDATING LOCAL FILE DATABASE\e[0m"
sudo updatedb
if [ $? == 0 ]; then
echo "The local file database was updated correctly."
else
echo "The local file database was not updated correctly."
fi
echo ""
# Installing and staring HTTPD service
echo -e "\e[4;32mInstalling HTTPD package\e[0m"
sudo yum install httpd -y
echo ""
echo -e "\e[4;32mStarting and enabling HTTPD package\e[0m"
sudo /etc/init.d/httpd start &&chkconfig httpd on
Visualpath Training &Consulting DevOps
Ph: 97044 55959, 96182 45689, onlinevisualpath@gmail.com, wwwvisualpath.in# 27
echo ""
# For CentOS 7
#sudo systemctl start httpd &&sudo systemctl enable httpd
# -Find and / or delete files with 777 permissions.
echo -e "\e[4;32mLOOKING FOR FILES WITH 777 PERMISSIONS\e[0m"
# Enable either option (comment out the other line), but not both.
# Option 1: Delete files without prompting for confirmation. Assumes GNU version of find.
#find -type f -perm 0777 -delete
# Option 2: Ask for confirmation before deleting files. More portable across systems.
find -type f -perm 0777 -exec rm -f {} +;
echo ""
ESHOLD=10
while read line; do
# This variable stores the file system path as a string
FILESYSTEM=$(echo $line | awk '{print $1}')
# This variable stores the use percentage (XX%)
PERCENTAGE=$(echo $line | awk '{print $5}')
# Use percentage without the % sign.
USAGE=${PERCENTAGE%?}
if [ $USAGE -gt $THRESHOLD ]; then
echo "The remaining available space in $FILESYSTEM is critically low. Used:
$PERCENTAGE"
fi
done <<(df -h -- total | grep -vi filesystem)







Automatic maintenance script for nginx service.
This Script starts nginx service if its dead.
Place it under cronjob and schedule to run every 2 minutes which acts as a monitoring and maintenance script.
Assumptions: Nginx is already installed on the system.
Continuous Integration Tools:
cat nginstart.sh

#!/bin/bash
if [ -f /var/run/nginx.pid ]
then
echo "Nginx is running."
else
echo "Starting nginx service."
service nginx start
fi

# crontab -e
* * * * * /opt/scripts/nginstart.sh

Example Script for automating Jenkins setup.


#!/bin/bash
# Author: Pavan Kumar Ranjit
## LOGIC TO CHECK THE TYPE OF DISTRIBUTION (REDHAT OR DEBIAN)
yum -- help >>/tmp/log1
if [ $? -eq 0 ]
## "$?"STORES THE EXIT CODE OF THE MOST RECENT COMMAND
then
echo "RPM Based OS Detected"
echo "Installing Java-JDK,Jenkins,Maven"
sleep 3
sudo yum install java-1.8.0- openjdk -y
sudo yum install java-1.8.0- openjdk-devel -y
sudo yum install wget -y
sudo wget -O /etc/yum.repos.d/jenkins.repo http://pkg.jenkins-ci.org/redhat/jenkins.repo
sudo rpm -- import https://jenkins-ci.org/redhat/jenkins- ci.org.key
sudo yum install Jenkins -y
sudo yum install maven -y
sudo yum install git -y
echo "Configuring services.... Please Wait"
sleep 5
sudo service iptables stop
sudo service Jenkins start
else
echo "Debian Based OS Detected"
sleep 3
echo "Installing Java-JDK,Jenkins,Maven"
sudo apt-get update
sudo apt-get install openjdk-8- jdk -y
sudo apt-get install openjdk-8- jre -y
sudo apt-get install maven -y
sudo apt-get install wget -y
wget -q -O - https://pkg.jenkins.io/debian/jenkins-ci.org.key | sudo apt-key add -
sudo sh -c 'echo deb http://pkg.jenkins.io/debian-stable binary/ >
/etc/apt/sources.list.d/jenkins.list'
sudo apt-get update -y
sudo apt-get install jenkins -y
sudo apt-get install git -y
echo "Configuring services.... Please Wait"
sleep 5
sudo systemctl stop ufw
sudo systemctl start jenkins
fi

For Example:
AWS
Azure
Google Cloud
Rackspace
Monitoring tools:
Is used to monitor our infrastructure and application health. It sends us notifications and reports through email or other means.
Summary:
Scripting is required for doing system tasks automatically without manual intervention.
Bash scripting is used by Linux System Admin for ages to automation Linux tasks.
Variables, Condition's, loops etc are important aspects of scripting language which helps us automate complex tasks.
Try all the sample and real-time use case scripts to get hold of system automation.
Conclusion:
There are so many advanced options in Bash Scripting like functions, list constructs, Regular Expressions etc, which you may be interested in and feel tempted to use them. You can check Advanced Bash Scripting guide http://tldp.org/LDP/abs/html/ for advanced
options.
Learning all those advanced options are great and make you a Scripting Guru if practised. There are also so many limitations to Bash script, like its only for Linux systems and there is so much of syntax in it.
Python should be your next choice of scripting language which is easier to read and write and is also versatile, it can be used to automate tasks on windows platform and cloud services also. Python has very less syntax for example check below “if condition” of bash vs python.
Bash way

#!/bin/bash a=5
if [ $a -lt 10 ]
then
echo "Variable is smaller than 10"
exit 1
fi

Python way

#!/usr/bin/python
a=10
if a <10:
print “variable is less than 10”

Both have their upsides and downside, you should make your choices wisely. But making choices comes with experience and practice. There is no perfect way of doing anything.
Practice makes improvement.

Comments