Skip to main content

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​

  1. Identify your local destination and remote target file.
  2. Set up key-based authentication for the server.
  3. Write a temporary batch of SFTP commands (e.g., get remote_file.txt).
  4. Execute sftp.exe and pass the batch commands using the -b flag.

Setup: Key-Based Authentication​

Because native sftp.exe does not accept passwords inline, you must use an SSH key pair.

  1. Generate a key using ssh-keygen.
  2. Place the public key in the remote server's ~/.ssh/authorized_keys file.
  3. 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?​

  1. Centralized Backups: Automating the nightly retrieval of database backups from external web servers into a single secure, local repository.
  2. Report Aggregation: Pulling daily transaction logs from vendor systems or remote branches for central processing.
  3. 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​

  1. Host Key Verification: The first time a machine connects via SFTP, the server's identity signature must be verified and added to the known_hosts file. A script cannot interactively answer "yes" to this prompt, so test the connection manually once before automating it.
  2. lcd vs get Pathing: While you can specify get /remote/file C:\local\file, using lcd (Local Change Directory) first makes the syntax cleaner and less prone to pathing errors, especially with spaces in folder names.
  3. 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.