用Ssh.Write()發送命令後,需等待執行完成再Ssh.ReadResponse()讀取完整輸出。Thread.Sleep不可靠(命令耗時不定)。
Linux Shell命令執行完畢會輸出提示符(如user@host:~$、root@server:#),以此為標誌判斷完成。
public string ExecuteCommand(string command, string promptRegex = @"[$#>]\s*$", int timeoutMs = 30000) {
ssh.Write(command + "\n");
StringBuilder output = new StringBuilder();
DateTime start = DateTime.Now;
string line;
while ((DateTime.Now - start).TotalMilliseconds < timeoutMs) {
line = ssh.ReadResponse(); // 非阻塞讀取可用數據
if (!string.IsNullOrEmpty(line)) {
output.Append(line);
// 檢測最後一行是否匹配提示符
string lastLine = line.Split('\n').LastOrDefault(l => !string.IsNullOrWhiteSpace(l));
if (Regex.IsMatch(lastLine, promptRegex)) {
break; // 命令執行完成
}
}
Thread.Sleep(50); // 避免忙等待
}
return output.ToString();
}
top、tail -f),需約定結束標記:ssh.Write("echo 'CMD_START'\n");
ssh.Write(command + "\n");
ssh.Write("echo 'CMD_END'\n");
// 讀取直到出現 CMD_END
ReadResponse()累積輸出,而非單次讀取。[$#>]\s*$覆蓋bash/zsh/root/common用戶,可配置化。ssh.Encoding匹配服務端Locale(通常UTF-8)。RunCommand、Expect模式、異步API。expect腳本(Linux原生)包裝複雜交互流程。