使用 WinSCP 和带有电子邮件通知的批处理文件自动 FTP 传输

Automated FTP transfer using WinSCP and Batch file with Email notification

我正在尝试编写一个批处理文件,它将:

问题解答:

@echo off

:: FTP Configuration
SET TRIES=2
SET INTERVAL=10
SET Server=user@server.com
SET HostKey=
SET ProdHostKey=ssh-rsa 2048 KeyKeyKeyKeyKeyKeyKeyKey
SET DRHostKey=ssh-ed25519 256 KeyKeyKeyKeyKeyKeyKeyKey
SET PrivateKey=C:\RSA_Privatekey\Key.ppk
SET Source=/Files/Work/
SET Destination=D:\Inbox\

:: Log File Configuration
SET DateStamp=%date:~-4,4%%date:~-10,2%%date:~-7,2%
SET LogFile=D:\Logs\WinSCP\WinSCP-FTP_%DateStamp%.log

:: Email Configuration
SET SMTPServer=smtp.server.com
SET EmailFrom=%computername%@server.com
SET EmailTo="email1@server.com", "email2@server.com"
SET EmailSubject="FTP Transfer Failure"
SET EmailAttachment="%LogFile%"
SET EmailBody="FTP transfer failed.`r`nLog file attached."

:Begin
SET HostKey=%ProdHostKey%

:Retry
:: Launch WinSCP
"C:\Program Files (x86)\WinSCP\WinSCP.com" ^
    /log="%LogFile%" /ini=nul ^
    /command ^
    "Option confirm off" ^
    "open sftp://%Server%/ -hostkey=""%HostKey%"" -privatekey=""%PrivateKey%"" -rawsettings ConsiderDST=0" ^
    "Get -delete "%Source%*.*" "%Destination%"" ^
    "Close" ^
    "Exit"

SET WINSCP_RESULT=%ERRORLEVEL%
if %WINSCP_RESULT% equ 0 (
    echo Success
    ) else (
            SET /A TRIES=%TRIES%-1
            IF %TRIES% GTR 1 (
                echo Transfer failed, retrying using DR hostkey, in %INTERVAL% seconds...
                timeout /t %INTERVAL%
                SET HostKey=%DRHostKey%
                goto Retry
            ) else (
                    echo Connection failed, aborting and sending an email notification.
                    echo.
                    echo From: %EmailFrom%
                    echo To: %EmailTo%
                    echo Subject: %EmailSubject%
                    echo Attachments: %EmailAttachment%
                    echo Message: %EmailBody%
                    powershell.exe -NoLogo -NoProfile -Command ^
                        "Send-MailMessage" ^
                            "-To %EmailTo%" ^
                            "-From '%EmailFrom%'" ^
                            "-Subject '%EmailSubject%'" ^
                            "-SmtpServer '%SMTPServer%'" ^
                            "-Body "%EmailBody%"" ^
                            "-Attachments %EmailAttachment%"
                            
                    exit /b 1
                    )
)

exit /b %WINSCP_RESULT%