Thursday, October 02, 2008

SSH Automation using Expect

Here's a cool script that will login to an SSH Server without prompting for a password. It can execute any start-up commands if needed.

The password is hard coded into the script which is lame, but this is my first attempt, I'm working on better/encrypted ways, but hey sometimes simple is best.

#!/usr/bin/expect -f
spawn ssh amol@sandbox

expect "amol@sandbox's password: "

send -- "PASSWORD\r"
expect "(sandbox:amol)$ "
send -- "pbsu -h sandbox root\r"
expect "Enter amol's pb-password:"
send -- "PASSWORD\r"
expect "(sandbox:root)# "
interact
# send -- "ksh -o vi\r"

# expect eof

Where:
Username : amol
Server : sandbox
Password: PASSWORD

The Last uncommented line "interact" is the point where you get the prompt for hand-typing commands. The script can be made Fully automatic by removing this statement.

The simplest way to remove the hard coded password would be to either prompt for it at stdin or to pass it using command line arguments. I'm thinking if we can do this in a more secure way like may be storing an encrypted passoword in a text file and then decrypting it on the fly while running the script. Storing it in a file will remove the need for a prompt and hence more convienient.

The Most secure way to do passwordless SSH automation is to use Public Key Authentication, however, if the SSH Server does not allow passwordless authentication then you cannot use it, which applied in my case.

Here's a good Tutorial on Expect.

0 comments: