Security it’s important, a host secured with a strong password is required, but sometimes we need to use other kind of authentification methods, in this article we will walk-through public and private key pair authentification and auto login with Expect script.
Tested operating systems: Debian 9.1, CentOS 7.3, FreeBSD 11.1 and macOS 10.12
Method 1 – Public and private key pair authentification
1. Generate RSA public and private key pair on the client host, ~/.ssh/id_rsa private and ~/.ssh/id_rsa.pub public key will be generated.
ssh-keygen -t rsa -f ~/.ssh/id_rsa -N ''
2. Append the public key to the ~/.ssh/authorized_keys file stored on the remote host through SSH
cat ~/.ssh/id_rsa.pub | ssh remote_user@remote_host 'cat >> ~/.ssh/authorized_keys'
Ready! Now you can login into remote_user@remote_host without password.
(Optional) If multiple private keys are used for different servers, we need to generate multiple key pairs and create ~/.ssh/config file.
ssh-keygen -t rsa -f ~/.ssh/id_rsa_remote_host1 -N ''
ssh-keygen -t rsa -f ~/.ssh/id_rsa_remote_host2 -N ''
cat ~/.ssh/id_rsa_remote_host1.pub | ssh remote_user@remote_host1 'cat >> ~/.ssh/authorized_keys'
cat ~/.ssh/id_rsa_remote_host2.pub | ssh remote_user@remote_host2 'cat >> ~/.ssh/authorized_keys'
echo "Host remote_host1" >> ~/.ssh/config
echo "Hostname remote_host1_ip_address" >> ~/.ssh/config
echo "IdentityFile ~/.ssh/id_rsa_remote_host1" >> ~/.ssh/config
echo "Host remote_host2" >> ~/.ssh/config
echo "Hostname remote_host2_ip_address" >> ~/.ssh/config
echo "IdentityFile ~/.ssh/id_rsa_remote_host2" >> ~/.ssh/config
ssh remote_user@remote_host1
ssh remote_user@remote_host2
Method 2 – Auto login with Expect script
1. Make sure that you have installed Expect and the PATH from the first line of the script it’s correct for example on FreeBSD 11.1 the PATH is /usr/local/bin/expect.
whereis expect
2. Create ssh.sh script with your favorite text editor and modify the user, password and port.
#!/usr/bin/expect -f
if {[llength $argv] < 1} {
puts "Usage: ./ssh.sh host";
exit 1;
}
set timeout 10
set host [lindex $argv 0]
set user "my_user"
set password "my_password"
spawn ssh $user@$host -p 22
expect {
"yes/no*" {
send "yes\n"
exp_continue
}
"?assword*" {
send "$password\n"
interact
exit 0;
}
}
exit 1
3. Change permission and execute.
chmod 700 ssh.sh
./ssh.sh host
Warning: Keep your private keys and scripts in secure places! Anyone who can read your files will be able to login into your hosts!