Automating SFTP using expect

I have to automate transferring of files and the only protocol I have available is SSH. I have accomplished this using expect and SFTP. I think it can help others too, so I am writing this article.

You can get Expect from http://expect.nist.gov

Expect: Expect is a tool for automating interactive programs. To use expect to automate file
Transfer with SFTP, we have to first create the expect script

#!/usr/local/bin/expect
spawn sftp -b cmdFile user@yoursftpserver.com
expect "password:"
send "password";
interact

This will spawn sftp in batch mode and pass in the password to the
program. SFTP will than execute all the commands in cmdFile

cmdFile
lcd /home/ftp/test1
cd
/home/ftp/somedir
mput *.xls
lcd /home/recieving
cd /home/somedir
mget *.xls

Another alternative would be to use Perl to automate the SCP.

Example:

#!/usr/bin/perl -w
use Net::SFTP;
use strict;
my $host = "server.com";
my %args = (
user =>
'your_user_name,
password =>
'your_password',
debug => 'true' );
my $sftp = Net::SFTP->new($host, %args);
$sftp->get("/home/user/something.txt", "/home/user/123.txt");
$sftp->put("abc", "xyz");

Leave a Comment

Your email address will not be published. Required fields are marked *

CAPTCHA * Time limit is exhausted. Please reload the CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top