Automating rsync with a Simple Expect Script
Expect is a great tool in a system administrators arsenal and can be used to easily automate tasks that require periodic user input. This can allow the administrator to make better use of their time than watching the application or utility to spot the next time it requires input.
In the following example expect is used to automate the inputing of a password for a series of rsync commands tunneled through ssh.
The script automates a series of rsync operations using only the password for access to the remote host so that the security of the two machines is not reduced by making the source machine trust the destination machine in any way (for example .rhosts or a ssh key with an empty pass phrase).
The script reads a password from the user and then holds that password in a variable for use each time the ssh application that rsync is using as a tunnel asks for it.
The "stty -echo" prevents the password from being echoed to the screen when it is typed in and the "stty echo" turns it back on.
#!/usr/bin/expect -f spawn date expect "#" send_user "The password for HOSTNAME: " stty -echo expect_user -re "(.*)\n" {set PASSPH $expect_out(1,string)} send_user "\n" stty echo set timeout -1 spawn date expect "#" spawn rsync -ave ssh --numeric-ids HOSTNAME:/etc /sdc/ expect "password:" { send "$PASSPH\n"} expect "#" spawn date expect "#" spawn rsync -ave ssh --numeric-ids HOSTNAME:/admin /sdc/ expect "password:" { send "$PASSPH\n"} expect "#" spawn date expect "#" spawn rsync -ave ssh --numeric-ids HOSTNAME:/home /sdd expect "password:" { send "$PASSPH\n"} expect "#" spawn date expect "#" spawn rsync -ave ssh --numeric-ids HOSTNAME:/mail /sdd expect "password:" { send "$PASSPH\n"} expect "#" spawn date expect "#" spawn rsync -ave ssh --numeric-ids HOSTNAME:/work /sdc/ expect "password:" { send "$PASSPH\n"} expect "#" spawn date expect "#"