SFTP(SSH File Transfer Protocol)是一種基於 SSH 協議的安全文件傳輸協議,提供加密傳輸通道,確保數據在傳輸過程中的機密性和完整性。類似於 HTTPS 之於 HTTP,SFTP 是 FTP 的安全增強版本。
在某個跨國專案中,需要將本地數據文件打包後通過 SFTP 傳輸至德國伺服器。為了實現自動化上傳,選擇了輕量級的開源工具 PSFTP(PuTTY 套件中的命令列 SFTP 客戶端)。PSFTP 是一個綠色單一 EXE 檔案,無需安裝,且在 C# 中透過 Process 類即可輕松調用,適合封裝為可重用元件。
PSFTP 採用類 Unix 命令風格,直觀易學。以下為核心命令示意圖:
常用命令包括:open(連線)、put(上傳)、get(下載)、cd(切換遠端目錄)、lcd(切換本地目錄)、quit(離開)等。
ProcessStartInfo,指定 PSFTP 路徑、參數(使用者、密碼、埠號、批次檔路徑等)。y 確認首次連線的金鑰提示。public string Upload()
{
string outPutMessage = "";
string scriptLocation = this.CreateScriptFile(); // 生成腳本檔
ProcessStartInfo processInfo = new ProcessStartInfo
{
FileName = this.m_ShellCommand, // PSFTP.exe 路徑
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardInput = true,
RedirectStandardOutput = true
};
// 組裝命令列參數
string arguments = $"{this.m_UserID}@{this.m_ServerName} ";
arguments += $"-pw {this.m_PassWord} ";
arguments += $"-P {this.m_Port} ";
arguments += $"-b {scriptLocation} ";
arguments += "-be"; // 遇錯不中斷
processInfo.Arguments = arguments;
using (Process process = new Process { StartInfo = processInfo })
{
try
{
process.Start();
// 自動應答首次連線的金鑰確認提示
process.StandardInput.WriteLine("y");
outPutMessage += process.StandardOutput.ReadToEnd();
outPutMessage += process.StandardError.ReadToEnd();
process.WaitForExit();
return outPutMessage;
}
catch (Exception ex)
{
throw new Exception("上傳文件至遠端伺服器時發生錯誤!", ex);
}
finally
{
File.Delete(scriptLocation); // 清理臨時腳本
}
}
}
private string CreateScriptFile()
{
StringBuilder sbdScript = new StringBuilder();
// 切換到遠端目標目錄
sbdScript.AppendLine($"cd {this.m_RemoteLocation}");
// 遍歷上傳文件列表,生成 put 命令
foreach (string file in this.m_UploadFiles)
{
sbdScript.AppendLine($"put {file}");
}
// 結束會話
sbdScript.Append("quit");
// 寫入臨時檔案
string scriptLocation = Path.Combine(this.m_TempLocation, $"{Guid.NewGuid()}.scr");
File.WriteAllText(scriptLocation, sbdScript.ToString());
return scriptLocation;
}
以下圖片展示了 ProcessStartInfo 關鍵屬性的配置細節:
SSH.NET(Renci.SshNet)等純托管庫,無需外部依賴,程式碼更優雅且跨平台。透過 C# Process 類調用 PSFTP,配合動態腳本生成,可快速構建穩定的 SFTP 自動化上傳功能。此方案部署簡單、依賴輕量,適合無法安裝完整 SSH 套件或需快速落地的場景。隨著 .NET Core / .NET 5+ 的普及,建議新專案優先評估原生托管庫以獲得更好的可維護性與跨平台能力。