SFTP server and client
Last week's README file demonstrated how easy it is to turn virtually any desktop machine into an SFTP server. Today's piece shows how to automate a well-known Windows open source SFTP client using script files.
WinSCP installation and settings
For this short tutorial I am using the WinSCP SFTP client for Windows. I installed WinSCP using the Custom Installation option, and at the Select Additional Tasks step, I made sure that Add installation directory to search path box was checked.
Checking this option helps to simplify WinSCP scripts and batch files -- this is because the full path of the WinSCP executable won't be needed in order to run the SFTP client from the command line.
Also, if possible, connect to the remote SFTP server first with the GUI application before connecting via the command line. Doing this allows you to easily add the remote server's host key to WinSCP's key cache.
I kick off SFTP scripts from the command line using a traditional batch file. For example, this is a listing of a batch file named deploy.bat -- used to start the SFTP client with script file. Notice the commented lines in the file, these lines are not needed if the option to add the WinSCP's folder to %PATH% was selected during installation.
REM Next line NOT needed if WinSCP folder was added to PATH
REM CD "C:\Program Files (x86)\WinSCP"
Notice too, the script file is named uploadscript.txt, specified by the /script parameter.
Finally, we examine the script file itself. In this example, I am opening a connection to an SFTP server (192.168.1.17) on my local network, specifying username (glasskeys) with password (somepassword). I then change the local directory to C:\temp, and instruct the SFTP client to copy a subfolder named "asubfolder", lastly, I instruct the client to copy a single document named atestdoc.txt to the remote server before exit:
option echo off
option batch on
option confirm off
#Change LOCAL directory lcd "C:\temp\"
#copy an entire folder
put -nopermissions -nopreservetime "asubfolder"
#copy an individual file
put -nopermissions -nopreservetime "atestdoc.txt" atestdoc.txt
You may be curious about the nopermissions and nopreservetime switches. WinSCP's put command documentation tells us that nopermissions keeps default file permissions, and nopreservetime instructs the remote server to replace timestamp information. Based on past experience, I've found that using both of these switches helps to mitigate problems -- especially when overwriting files on remote SFTP servers.
This is a screenshot of the deploy batch file executing in a command window:
For more information, consult WinSCP's extensive scripting documentation here.
This article is published as part of the IDG Contributor Network. Want to Join?