0

This is probably a question asked before, but I can't find a good question/answer. I need to write a shell script that will be called by PHP program (exec function) to move all *.pdf files to a remote directory via SFTP. The target directory will be constant. The remote directory will also be constant. The files will only be of *.pdf format.

The script must use SFTP, this is a requirement. It SCP will not work. The SFTP port is also custom, I'll have to work that into the code below. I'm not sure how to write the loop thru the *.pdf files in the directory and then remove them on success. Perhaps a slightly different approach would be better.

#! /bin/ksh
TARGET_DIR=<path of target directory>
FILE_NAME_TO_CHECK=<file_name>
REMOTE_USER=<user_name>
REMOTE_PORT=<remote port>
REMOTE_MACHINE=<remote server name>
REMOTE_DIR=<path of remote directory>

cd ${TARGET_DIR}
sftp ${REMOTE_USER}@${REMOTE_MACHINE} -
3

You should use private key authentication to avoid problems with passwords.

sftp -oPort=CUSTOMPORT -b BATCHFILE USER@DESTINATION

BATCHFILE (prepare it before launching the command)

lcd LOCAL_PATH
cd REMOTE_TARGET_DIR
put *.pdf
exit
0

You can automate SFTP file upload using WinSCP, if you already know the sequence of commands you would use to do it manually. I've copied the sample script from the answer below:

echo option batch abort > ftpcmd.dat
echo option confirm off >> ftpcmd.dat
echo open sftp://ftp_user:password@ftp.MyFTPSite.com -hostkey="server's hostkey" >> ftpcmd.dat
echo put directory_path\%.pdf >> ftpcmd.dat
winscp.com /script=ftpcmd.dat
del ftpcmd.dat

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.