How to Download a File from an SFTP Server in Batch Script
Downloading files securely is just as crucial as uploading them. Automating the retrieval of log files, daily configuration backups, or third-party reports via SFTP (SSH File Transfer Protocol) ensures that sensitive data remains encrypted in transit. In Modern Windows, the built-in OpenSSH client (sftp.exe) makes this possible directly from a Batch script.
In this guide, we will demonstrate how to automate an SFTP file download using native tools.
The Strategy: The OpenSSH Client
- Identify your local destination and remote target file.
- Set up key-based authentication for the server.
- Write a temporary batch of SFTP commands (e.g.,
get remote_file.txt). - Execute
sftp.exeand pass the batch commands using the-bflag.
Setup: Key-Based Authentication
Because native sftp.exe does not accept passwords inline, you must use an SSH key pair.
- Generate a key using
ssh-keygen. - Place the public key in the remote server's
~/.ssh/authorized_keysfile. - Secure your private key locally (e.g.,
C:\Users\Admin\.ssh\id_rsa).
Implementation Script
@echo off
setlocal enabledelayedexpansion
:: 1. Define Connection Details
:: Format: username@hostname
set "sftpTarget=admin@sftp.example.com"
:: Path to your private key file
set "privateKey=C:\Users\Admin\.ssh\id_rsa"
:: Remote directory and file path
set "remotePath=/var/log/daily_report.zip"
:: 2. Define Local Destination
set "localDir=C:\Downloads\Reports"
:: Ensure local directory exists
if not exist "%localDir%" mkdir "%localDir%"
:: 3. Create a temporary SFTP command file
:: Note: Lines starting with :: inside a parenthesized block can cause
:: errors. Use REM or remove comments from within the block.
set "sftpCommands=%TEMP%\sftp_download.txt"
(
echo lcd "%localDir%"
echo get "%remotePath%"
echo bye
) > "%sftpCommands%"
echo Downloading "%remotePath%" from %sftpTarget% to "%localDir%"...
echo.
:: 4. Execute SFTP Download
:: -b specifies the batch file containing the commands
:: -i specifies the identity (private key) file
sftp -i "%privateKey%" -b "%sftpCommands%" "%sftpTarget%"
:: Capture the exit code immediately
set "sftpResult=!errorlevel!"
:: 5. Cleanup the temporary command file
del "%sftpCommands%" 2>nul
:: 6. Validate the result
if !sftpResult! equ 0 (
echo.
echo ==========================================
echo DOWNLOAD SUCCESSFUL
echo ==========================================
) else (
echo.
echo [ERROR] Download failed with exit code !sftpResult!. Check connectivity and keys.
pause
exit /b 1
)
endlocal
pause
exit /b 0
Why Download via SFTP?
- Centralized Backups: Automating the nightly retrieval of database backups from external web servers into a single secure, local repository.
- Report Aggregation: Pulling daily transaction logs from vendor systems or remote branches for central processing.
- Encrypted Transport: SFTP encrypts the connection entirely, securing data unlike older FTP implementations.
WinSCP Alternative (For Passwords)
If your environment strictly requires password authentication and you cannot use SSH keys, you must use a third-party tool like WinSCP.
@echo off
setlocal enabledelayedexpansion
:: Define paths
set "winscpPath=C:\Program Files (x86)\WinSCP\WinSCP.com"
set "localDir=C:\Downloads\Reports"
:: Verify WinSCP is installed
if not exist "%winscpPath%" (
echo [ERROR] WinSCP not found at "%winscpPath%".
pause
exit /b 1
)
:: Ensure local directory exists
if not exist "%localDir%" mkdir "%localDir%"
echo Downloading file via WinSCP...
:: WinSCP script for password-based SFTP downloads
:: WARNING: -hostkey="*" disables host key verification. In production,
:: replace * with the actual server fingerprint for security.
"%winscpPath%" /command ^
"open sftp://admin:Password123@sftp.example.com/ -hostkey=""*""" ^
"get /var/log/daily_report.zip ""%localDir%\""" ^
"exit"
:: Capture the exit code immediately
set "winscpResult=!errorlevel!"
if !winscpResult! equ 0 (
echo [SUCCESS] File downloaded successfully to "%localDir%".
) else (
echo [ERROR] WinSCP download failed with exit code !winscpResult!.
pause
exit /b 1
)
endlocal
pause
exit /b 0
Important Considerations
- Host Key Verification: The first time a machine connects via SFTP, the server's identity signature must be verified and added to the
known_hostsfile. A script cannot interactively answer "yes" to this prompt, so test the connection manually once before automating it. lcdvsgetPathing: While you can specifyget /remote/file C:\local\file, usinglcd(Local Change Directory) first makes the syntax cleaner and less prone to pathing errors, especially with spaces in folder names.- Private Key Permissions: The OpenSSH client strictly enforces access controls. Ensure your private key file (
-i) is only readable by the Windows user running the script.
Conclusion
Automated SFTP downloads are the bedrock of reliable external data synchronization. By scripting the native sftp.exe utility, Windows administrators can safely pull vital files from Linux/UNIX endpoints natively. Integrating key-based authentication with temporary command batching transforms manual download routines into unassisted, highly secure automated workflows.