Wednesday, October 7, 2020

Unix - Shell Script - Connect to SFTP from script

Description:

This post cover various ways to connect to SFTP from shell script. Passing the password in the command prompt is easier and secure as user is explicitly typing it down when prompted. But in shell script, password needs to be passed automatically and securely.

Approach-01: using sshpass command

Resource-01 covers detail about the command and how to install in various version on unix.  

SFTP_USER=<user>
SSHPASS=<password>
TARGET_SERVER=<host>
sshpass -e sftp -oBatchMode=no -b - $SFTP_USER@$TARGET_SERVER <<EOF ls -lrt cd <target path> put <source path/file name> bye EOF

Approach-02: using lftp command

SFTP_USER=<user>
LFTP_PASSWORD=<PASSWORD>
TARGET_SERVER=<host>

lftp --env-password sftp://$SFTP_USER@$TARGET_SERVER <<EOF
    ls -lrt
    cd <target path>
    put <source path/file name>
    bye
EOF

Resources:

  1. Detail about 'sshpass' command. How to install the command, various ways to pass password to connect to SFTP etc. 

    https://www.cyberciti.biz/faq/noninteractive-shell-script-ssh-password-provider/