Sunday, June 8, 2008

Scripting SCP

I love scp, its easily one of the most used unix commands in my tool bag. That said it is a real pain inf the butt to try and script scp. I was in the midst of writing a little script that would create ssh key pairs and distribute them to a number of servers. On paper this seemed to be almost trivial and that my friends is the problem wit paper. In order to make scp more secure the developers had it communicate using PAM instead stdin, sterr and stdout. Bummer, This meant there was no easy way to supply scp with the users password. So there is no command line option to supply the password and I can't write to it over stidn, I was a little stuck. After searching that Internet, and I mean really scouring, I found a command called expect. Using this I wrote a quick and dirty shell script to do the scp part:

#!/usr/bin/env expect -f
set password [lindex $argv 0 ]
set file [lindex $argv 1 ]
set command [lindex $argv 2 ]

# trick to pass in command-line args to spawn
eval spawn scp -r $file $command

expect "password: $"
send "$password\n"

# wait for regular shell prompt before quitting
# probably a better way using 'wait'
expect "$ $"

With this the whole scripting experience became trivial again, rock on!

1 comment:

Anonymous said...

Your blog keeps getting better and better! Your older articles are not as good as newer ones you have a lot more creativity and originality now keep it up!