Skip to content

How to run a script for a interactive command

Using shell scripts can greatly improve our work efficiency. There are many tutorials about how to write shell scripts on the Internet, but it‘s difficult to find how to create scripts for interactive programs such as sftp. I will record my practice in this article for future reference.

Method 1

Using the EOF syntax

The EOF syntax is very useful when working with multi-line text in Bash.

SERVER_IP=ftps_server_ip_or_domain
SERVER_PORT=port
USER=user_name

echo "Script for SFTP begin"
sftp -P $SERVER_PORT $USER@$SERVER_IP <<EOF
cd path_in_sftp_server
lcd path_in_local_host
get -r directory_in_ftps_server
bye
EOF
echo "Script for SFTP end"

“<< EOF” tells the shell that you are going to enter a multiline script until the “EOF” after, and the multiline script will be excute on sftp program.

Note: You will be asked to enter a password to log in to the SFTP server. If you do not want to enter it, you can use the sshpass tool to log in to the SFTP server. Replace the sftp login commad above with following command.

sshpass -p "your_password" sftp -o StrictHostKeyChecking=no sftp -P $SERVER_PORT $USER@$SERVER_IP

Method 2

Using the expect tool

the expect tool is not installed on Ubuntu by default, we should install it first.

sudo apt-get install expect

The following is an example of runing script on SFTP command.

#!/usr/bin/expect

set SERVER_IP ftps_server_ip_or_domain
set SERVER_PORT port
set USER user_name
set PASSWD user_passwd

spawn sftp -P $SERVER_PORT $USER@$SERVER_IP #spawn opens a new process
expect "*password*" #wait until "password" outputs
send "${PASSWD}\r" #send password to sftp
expect "*sftp*" #wait for sftp ready
send "lcd path_in_local_host\r"
expect "*sftp*"
send "cd path_in_sftp_server\r"
expect "*sftp*"
send "get -r directory_in_ftps_server\r"
expect "*sftp*"
send "bye\r"

Note: The script above must be excuted by /usr/bin/expect.

Leave a Reply