This tutorial explains how to automatically login with a password when connecting to ssh.
After reading this tutorial, you’ll know how to implement a script to automatically login with passwords to connect to ssh. Additionally, you’ll find instructions for automatic ssh password login using the sshpass tool. Finally, this tutorial explains how to connect without a password with public key authentication.
How to script ssh login with passwords:
To begin, install expect by running the command below.
Create a shell script by running the command below. You can use any arbitrary name for your script.
Copy the following code within the file, replacing [email protected] with your username and server. Also, replace passwordhere with your actual password.
spawn ssh linuxhint@192.168.1.103
expect "Password:*"
send "passwordhere\r"
expect "$ "
interact
Give the script execution rights by running the command shown in the screenshot below, replace sshscript.sh with your script name.
Then, run the script, and you’ll connect automatically without needing to type your password, as shown in the following image.
How to automatically ssh login with passwords using sshpass:
Another option to connect through ssh with automatic password login is the sshpass tool. Although you can install sshpass using apt, yum, or any other packages manager, it is recommended to download its last version and install from sources. Some users reported problems with old versions found in some package managers.
To download the sshpass current version, run the command below.
Extract the .tar.gz package using the command below.
Enter the installation directory.
Run the following command to install sshpass.
Once installed, run the command below to connect to your server. Replace the passwordhere with your actual password. Also, replace [email protected] with your username and server IP.
As you can see, the connection was done properly.
Connect to ssh without password using public key authentication:
A better and more secure way to connect without needing to type your password is using public keys.
Generate public and private keys from the client you want to connect from by running the command below. When requested to type a passphrase, leave the field empty and press ENTER.
Now you need to copy the public key to the server you want to connect to. To copy the public key to the server, run the command below, replacing linuxhint with your actual username and 192.168.1.103 with your server IP address.
Once the public key is copied to the server, you can connect by running the following command. Replace the username and the IP address with yours.
Conclusion:
I hope this tutorial explaining how to script ssh login with passwords was useful. Keep following Linux Hint for additional Linux tips and tutorials.