Tuesday, January 26, 2010

Automating sftp with expect script

I got a request to automate the sftp process. I find it difficult with shell script. I find an easy way to do with
expect script.


The following packages need to be installed on the SUN server for the expect script. I downloaded the x86packages from sun freeware as I'm running the script from an x86 server.

tcl-8.5.3-sol10-x86-local
libgcc-3.4.6-sol10-x86-local
expect-5.43.0-sol10-x86-local


1)pkgadd -d tcl-8.5.3-sol10-x86-local

2)pkgadd -d libgcc-3.4.6-sol10-x86-local

The following packages are available:
  1  SMClgcc346     libgcc
                    (x86) 3.4.6
Installation of was successful.

3)pkgadd -d expect-5.43.0-sol10-x86-local 

 
The following packages are available:
  1  SMCexpect     expect
                   (x86) 5.43.0
Installation of was successful.


The expect will installed in the /usr/local/bin directory.

The script is as follows

----------------------------------------------------------------------------------------------------------
#!/usr/local/bin/expect -f
#This is the expect script wrote to automate the sftp process to pull files from a server as per the date and #then push the files to another server.
set timeout -1
set DATE [exec date "+%Y%m%d"]
log_file  "/home/ftp/logs/sftp.log"
send_log --  "####-Starting  SFTP script-  [exec date] \n"
send_log --  "Today's date:[exec date] \n"
send_log --  "Downloading files through sftp \n"
spawn /usr/bin/sftp jim@172.20.1.86
expect "Password:"
#sleep 5
send "jim123\n"
expect "sftp>"
send "cd /export/home/jim \r"
expect "sftp>"
send "ls \r"
expect "sftp>"
send "get *.$DATE \r"
expect "sftp>"
send "quit \r"
sleep 5
send_log --  "Today's date:[exec date] \n"
send_log --  "Uploading files through sftp \n"
spawn /usr/bin/sftp jim@172.20.5.93
expect "Password:"
send "jim123\n"
expect "sftp>"
send "cd /export/home/jim \r"
expect "sftp>"
send "put *.$DATE \r"
expect "sftp>"
send "quit \r"
#END of SCRIPT
-----------------------------------------------------------------------------------------------------------

I can shell script from expect script. I have another requirement to pull yesterdays file through sftp server. Thank god that was a Linux server and to get yesterdays date in Linux is easy :)

set DATE [exec /home/ftp/date.sh ]

The above line will call the date.sh script to get yesterdays date. 
date.sh script is as below

[root@]# cat date.sh
#!/bin/bash
echo $(date  --date='1 day ago' "+%Y%m%d")
#End of script