Method 2: use sshpass to provide password with ssh
sshpass is a utility designed for running ssh using the mode referred to as “keyboard-interactive” password authentication, but in non-interactive mode. This rpm is provided as part of EPEL repository and does not requires a key for performing SSH.
Make sure EPEL repository is installed on your server:
~]# rpm -q epel-release epel-release-8-8.el8.noarch
If it is not installed, then you can install the same using:
~]# dnf -y install epel-release
You can search for this package in the repository
~]# dnf search sshpass
Last metadata expiration check: 0:00:27 ago on Thu 17 Sep 2020 01:25:51 PM IST.
===================================== Name Exactly Matched: sshpass =====================================
sshpass.x86_64 : Non-interactive SSH authentication utility
Let’s quickly install this rpm for the demonstration:
~]# dnf install sshpass -y
Method 3: using private public passphrase instead of password
This is definitely the most recommended method to use ssh if you want to automate the SSH process. I have already written a well detailed article on how SSH public key based authentication works. There are 6 different types of authentication methods with SSH but we will for now concentrate on public key based authentication for this tutorial.
Method 4: using pssh and pscp
We also have a very handy tool written in python i.e. PSSH and PSCP where you can connect to multiple hosts by just entering the password once on the terminal. You can also setup password less login using private public key pair and then use the public key to connect to remote server without any password.
PSSH is part of EPEL repository which we had already installed in our previous section so we will just install PSSH.
~]# dnf -y install pssh
Next we will generate a password less private public key pair
Scenario-1: create a password less passphrase to perform ssh
In this example we create a password less key pair so that the SSH won’t prompt for any password. Use ssh-keygen to generate a key pair with -P “” to provide an empty password
Scenario-1: use separate expect script
Below is a sample expect script which can use used to perform SSH and execute a command, the password is provided internally in the script:
Scenario-2: automate ssh with passphrase
In the previous scenario we had set an empty passphrase for the key pair but what if you have set a passphrase. In that case the script will still prompt for a passphrase. We cannot avoid this scenario but if you have multiple hosts then we do can make sure that you get a passphrase prompt only once and SSH will continue to connect all the hosts. Now this is only possible if all these hosts are configured with the same private public key pair.
We generate a passphrase based key pair where our passphrase will be “redhat”
Scenario-2: perform scp using sshpass
You can also transfer files without getting a password prompt by combining scp with sshpass. In this example we copy a file /tmp/src_file to our remote server with scp and sshpass
~]# sshpass -p 'redhat' scp /tmp/src_file root@192.168.43.154:/tmp/
Here ‘redhat’ is my password.
Scenario-2: use expect inside bash script
Now this was a separate expect script but you can choose to integrate it inside a shell script which would look like below. I have moved the input argument inside the bash script instead of expect but that is totally upto you, there is no such restriction what so ever.
Scenario-3: perform scp with password using expect
We can also transfer files to another server without getting a password prompt using expect script. Here is one example which uses a separate expect script to transfer /tmp/src_file to target host:
Scenario-3: use file descriptor with sshpass
This is the most recommended method to use sshpass wherein we provide the password as a file descriptor instead of plain text. This part of code snippet is taken from stackoverflow
Write a shell script to ssh to a remote machine and execute commands
There is are multiple ways to execute the commands or script in the multiple remote Linux machines.
One simple & easiest way is via pssh (parallel ssh program)
pssh: is a program for executing ssh in parallel on a number of hosts. It provides features such as sending input to all of the processes, passing a password to ssh, saving the output to files, and timing out.
Example & Usage:
Connect to host1 and host2, and print “hello, world” from each:
pssh -i -H "host1 host2" echo "hello, world"
Run commands via a script on multiple servers:
pssh -h hosts.txt -P -I<./commands.sh
Usage & run a command without checking or saving host keys:
pssh -h hostname_ip.txt -x '-q -o StrictHostKeyChecking=no -o PreferredAuthentications=publickey -o PubkeyAuthentication=yes' -i 'uptime; hostname -f'
If the file hosts.txt has a large number of entries, say 100, then the parallelism option may also be set to 100 to ensure that the commands are run concurrently:
pssh -i -h hosts.txt -p 100 -t 0 sleep 10000
Options:
-I: Read input and sends to each ssh process.
-P: Tells pssh to display output as it arrives.
-h: Reads the host’s file.
-H : [user@]host[:port] for single-host.
-i: Display standard output and standard error as each host completes
-x args: Passes extra SSH command-line arguments
-o option: Can be used to give options in the format used in the configuration file.(/etc/ssh/ssh_config) (~/.ssh/config)
-p parallelism: Use the given number as the maximum number of concurrent connections
-q Quiet mode: Causes most warning and diagnostic messages to be suppressed.
-t: Make connections time out after the given number of seconds. 0 means pssh will not timeout any connections
When ssh’ing to the remote machine, how to handle when it prompts for
RSA fingerprint authentication.
Disable the StrictHostKeyChecking to handle the RSA authentication prompt.
-o StrictHostKeyChecking=no
Source: man pssh
Как ввести пароль в bash через скрипт?
При подключении к серверу по SSH через скрипт есть надобность ввести пароль.
Получается так, что, при подключении к серверу он запрашивает пароль:
ssh server@192.168.1.101 //Выполняю команду
server@192.168.1.101's password: //Выводит консоль
Адреса постоянно меняются, пароли приходят извне.
Как через скрипт ввести пароль?
Conclusion
In this tutorial we covered different scenarios to automate SSH with password in shell scripts with different methods. The most recommended and secure method is Public key authentication followed by SSHPASS with descriptor. You may also choose to use expect script which is also preferred but the only problem would be lack of security as the password would be in plain text format.
Lastly I hope the steps from the article to configure ssh with password in Linux was helpful. So, let me know your suggestions and feedback using the comment section.