Automatic Batch Sftp With Expect
Wednesday, June 11th, 2008Expect is a tool for automating interactive applications such as telnet, ftp, passwd, fsck, rlogin, tip, etc.
This code helps use to understand how to use command line arguments and string concatenation with Expect and with any Tlc scripts.
/usr/bin/expect
# This line is if you want to use a file with the list of the commands.
# You'd need an authentication without password
# spawn sftp -b /home/daniele/Desktop/projects/pdf/script/cmdFile webdev@89.234.32.214
# This line is the simple login, instead
spawn sftp webdev@89.234.32.214
expect "assword:"
# You can send the password automatically if you feel confortable
# in writing it in this line
#send "My Password\n";
# Otherwise there is this more safe way (not automatic)
stty -echo
expect_user -re "(.*)\n"
send_user "\n"
send "$expect_out(1,string)\r"
stty echo
# At this point, we can expect two different replays
# depending if the password was correct or not.
expect {
# This line "catches" the case you write a wrong password
# In this case, we prefer to stop the process because the
# re-tried password could be output in cleartext
# Actually this issue could be handled in a better way
"ermission" {
puts "PLEASE, DON'T WRITE YOUR PASSWORD AGAIN"
puts "RE-RUN THE PROGRAM, INSTEAD"
exit
}
"sftp>" {
send "\n";
}
}
# Now the list of commands (in the case you are not using the first type of auth that is with the -b flag)
expect "sftp>"
send "cd /var/cc-pdfs/au-live/fault/\n";
expect "sftp>"
send "lcd /home/daniele/Desktop\n"
# command line argument
set in_arg [lindex $argv 0]
set get_command "get CC_$in_arg.pdf\n"
expect "sftp>"
send $get_command
expect "sftp>"
send "exit\n";

