Since I mentioned public key authentication is more preferred, why are we still interested in the method that we are going to explore next? Well in some machines or environments, public key authentication was not setup and you might not have the privelleges to set it up. If you happened to be in the senario decribed above and are in a hurry to ssh to a large number of machines to perform some tasks, below method might come in handy for you.
Step 1
Create a custom script using expect scripting language. As an example name the script as auto_login. The first line of the script should look like below.
#!/usr/bin/expect |
Step 2
Setup three variables that will store user input for ssh login process. Basically these are hostname, userid and password.
set hostname [lindex $argv 0] set pwd [lindex $argv 1] set userid [lindex $argv2] |
Step 3
Provide the syntax that will initiate the ssh process using the variables defined in step 2.
spawn ssh "$userid\@$hostname" |
Step 4
Provide the syntax on what condition the script to start inputing the password. Usually it will be at the prompt for password. Notice the letter "P" is omitted below. This is due to some prompt wil use "P" and some "p".
expect "assword:*" |
Step 5
Provide the syntax to input the password and give you the session for your task after login.
send "$pwd\r" interact |
Basically the whole script will look like below.
#!/usr/bin/expect set hostname [lindex $argv 0] set pwd [lindex $argv 1] set userid [lindex $argv2] spawn ssh "$userid\@$hostname" expect "assword:*" send "$pwd\r" interact |
Now you can try to test it out.
./auto_login "hostname" "password" "userid" |