You can always configure passwordless ssh in order to transfer files using sftp without user being asked for a password. But if its not allowed to configure a passswordless ssh, there is a way to automate sftp file transfers. It can be achieved by using ‘expect‘ command provided by the tcl shell.
For the expect utility to work we need to install the “expect” package. To do so use the below command :
# yum install expect
Below is an example script that automates remote access with a batch file.
#!/bin/bash if (( $# < 3 )); then echo "Usage: $0 [remote addr] [password] [batch file]" echo echo -e "tremote addr : [loginid]:[host addr]n" exit fi REMOTE=$1 PASS=$2 BATCH=$3 expect -c " spawn sftp -o "batchmode no" -b "$BATCH" $REMOTE expect -nocase "password:" {send "$PASSr"; interact} "
Here,
spawn - to initiate the sftp process expect - it expects a particular string ( here it is "password:" prompt ) send - sends the password when the expect utility gets the required prompt.
Here's an example how to run the script which run the commands in testjob.bat on remote.example.com after log in as root with a password 'password'
# bash ./test.sh root@remote.example.com password testjob.bat