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

问题描述

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

  • 使用WinSCP连接到FTP服务器
  • 使用RSA密钥进行身份验证
  • 尝试两个不同的密钥,以防一个失败
  • 发送有关失败转移的电子邮件通知
  • 保存日志

解决方法

问题的解决方案:

@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%