How to Upload a File to an SFTP Server from a Batch Script
Transferring files securely over the internet is a fundamental task for system administrators. While older scripts relied on plain FTP, modern security standards demand SFTP (SSH File Transfer Protocol). Natively, Batch scripts do not have an SFTP client, but Windows 10 and 11 now include OpenSSH (sftp.exe) by default, making secure automated uploads straightforward. Optionally, robust third-party tools like WinSCP are also widely used.
In this guide, we will demonstrate how to upload a file to an SFTP server using the native Windows sftp command.
The Strategy: The OpenSSH Client
- Identify your local file and remote destination.
- Set up key-based authentication (to avoid interactive password prompts).
- Write a temporary batch of SFTP commands (e.g.,
put filename.txt). - Execute
sftp.exeand pass the batch commands using the-bflag.
Setup: Key-Based Authentication
The native sftp.exe does not accept a password in the command line for security reasons. To automate it, you must generate an SSH key pair (ssh-keygen) and place the public key on the remote server (~/.ssh/authorized_keys).
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 path
set "remotePath=/var/www/uploads/"
:: 2. Define File to Upload
set "localFile=C:\Reports\Daily_Report.pdf"
if not exist "%localFile%" (
echo [ERROR] The file "%localFile%" does not exist.
pause
exit /b 1
)
:: 3. Create a temporary SFTP command file
:: Quote paths to handle directories or filenames containing spaces
set "sftpCommands=%TEMP%\sftp_upload.txt"
(
echo cd "%remotePath%"
echo put "%localFile%"
echo bye
) > "%sftpCommands%"
echo Uploading "%localFile%" to %sftpTarget%...
echo.
:: 4. Execute SFTP Upload
:: -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 UPLOAD SUCCESSFUL
echo ==========================================
) else (
echo.
echo [ERROR] Upload failed with exit code !sftpResult!. Check connectivity and keys.
pause
exit /b 1
)
endlocal
pause
exit /b 0
Why Upload via SFTP?
- Secure Log Aggregation: Pushing security logs from multiple isolated servers to a centralized, hardened log server nightly.
- Web Deployments: Using a build script to compile static HTML or PDF reports, and immediately deploying them to a public-facing web server's
/var/www/directory. - Encrypted Transport: Unlike plain FTP (which transmits files and credentials in cleartext), SFTP encrypts the entire connection, ensuring compliance with data security policies.
WinSCP Alternative (For Passwords)
If you absolutely cannot use SSH keys and must authenticate via a password, the native OpenSSH client will not work within an automated batch script. You must use a third-party utility like WinSCP.
@echo off
setlocal enabledelayedexpansion
:: Define paths
set "winscpPath=C:\Program Files (x86)\WinSCP\WinSCP.com"
set "localFile=C:\Reports\Daily_Report.pdf"
:: Verify WinSCP is installed
if not exist "%winscpPath%" (
echo [ERROR] WinSCP not found at "%winscpPath%".
pause
exit /b 1
)
:: Verify the local file exists
if not exist "%localFile%" (
echo [ERROR] The file "%localFile%" does not exist.
pause
exit /b 1
)
echo Uploading "%localFile%" via WinSCP...
:: WinSCP script for password-based SFTP uploads
:: 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=""*""" ^
"put ""%localFile%"" /var/www/uploads/" ^
"exit"
:: Capture the exit code immediately
set "winscpResult=!errorlevel!"
if !winscpResult! equ 0 (
echo [SUCCESS] File uploaded successfully.
) else (
echo [ERROR] WinSCP upload failed with exit code !winscpResult!.
pause
exit /b 1
)
endlocal
pause
exit /b 0
Important Considerations
- Host Key Verification: The first time you connect to an SFTP server, SSH asks you to verify the host key (the "Are you sure you want to continue connecting?" prompt). Because a batch script cannot answer this, connect manually once to add the server to your
known_hostsfile before scheduling the script. - Private Key Permissions: The OpenSSH client strictly enforces permissions on the private key file (
-i). If the key file is accessible to other users,sftpwill reject it as "too open." Ensure the key file is locked down to your user account only.
Conclusion
Uploading files to external servers securely and automatically is a critical capability for any IT infrastructure. By utilizing the built-in OpenSSH client (sftp.exe) paired with key-based authentication, your Batch scripts can integrate natively with robust UNIX/Linux file systems encrypting transfers entirely from end to end. Alternatively, wrapping WinSCP covers legacy scenarios requiring passwords.