Sunday, April 29, 2007

Expect

Today I was writing an installer to install a few scripts that will aid build automation and uploading of reports generated from Clear Case to web. I was faced with this particular problem.

Problem: I wanted a remote site to generate a secret key and upload to my machine. I did not want to write a readme describing how to do that since I was sure that the guy on the other side will come back to me asking me to explain it.

This is what I did:

I wrote two expect scripts and wrote a shell script to call them with required arguments. The first script generated the key & the second uploaded it to my server.

---- Script to generate an RSA key. ----
---- Call only if the keys are not present ----
spawn ssh-keygen -t rsa
expect {
-re "Generating*" {exp_continue}
-re "Enter*" {send "\r";exp_continue}
timeout {puts TimeErr}
}
Then I wrote another script to put it where I wanted

--------------------Scp script --------------------------------
set USER [lindex $argv 0]
set RHOST [lindex $argv 1]
set RPASS [lindex $argv 2]
set DESTFILE [lindex $argv 3]
set HOME [lindex $argv 4]
spawn scp $HOME/.ssh/id_rsa.pub \ $USER@$RHOST:$DESTFILE
expect {
-re "^The" {send "yes\r"}
-re "^$USER" {send "$RPASS\r"; exp_continue;}
timeout {puts TimeErr}
}
spawn ssh $USER@$RHOST "if \[ ! -f\ ~/.ssh/authorized_keys \]; then mkdir -p ~/.ssh ; touch \ ~/.ssh/authorized_keys; fi; cat ~/$DESTFILE >>\ ~/.ssh/authorized_keys"
expect {
-re "^The" {send "yes\r"}
-re "^$USER" {send "$RPASS\r"; exp_continue;}
timeout {puts TimeErr}
}

This was my first attempt with expect. Needless to say, I really enjoyed doing this and now I want to learn expect better.

No comments: