为了在 SSH.NET 的单个会话中发送多个命令,您可能需要使用ShellStream。这应该会将您的 2FA 批准减少到仅向主持人开放会话。这对于不支持命令通道但支持 SSH 远程终端的设备(例如 HPE 交换机)也很有用(例如,您可以对它们进行腻子处理),以及命令更改(shell)环境等的情况您需要在工作期间保持会话打开。否则,SSH 命令通道是处理此问题的预期(和更好)方式。
您可以在 NuDoc - SSH.NET 找到更多 SSH.NET 文档,SSH.Net 项目的 GitHub 版本包括 Windows Help file。
这是我编写的一些代码,用于将 ShellStream 包装在另一个对象中,该对象保留 StreamReader 和 StreamWriter 并处理从 (n HP) 开关读取输入并过滤掉转义序列,以及向上读取到下一个提示:
public static class SshClientExt {
public static ExtShellStream CreateExtShellStream(this SshClient sc, string termName, uint rows, uint cols, uint width, uint height, int bufSize) =>
new ExtShellStream(sc.CreateShellStream(termName, rows, cols, width, height, bufSize));
}
public class ExtShellStream : IDisposable {
static Regex reEscVT100 = new Regex("\x1B\\[[^A-Z]+[A-Z]", RegexOptions.Compiled);
static TimeSpan ReadTimeout = new TimeSpan(0, 0, 10);
ShellStream ssh;
StreamReader sr;
StreamWriter sw;
public ExtShellStream(ShellStream anSSH) {
ssh = anSSH;
sr = new StreamReader(ssh);
sw = new StreamWriter(ssh);
}
public List<string> ReadLines() {
// try to read all in
long prev;
do {
prev = ssh.Length;
Thread.Sleep(250);
} while (ssh.Length != prev);
"-".Repeat(40).Dump();
var ans = new List<string>();
while (true) {
var line = sr.ReadLine();
if (line != null) {
line = line.Remove(reEscVT100).TrimEnd();
$@"""{line}""".Dump();
if (line.EndsWith("#")) // stop when prompt appears
break;
else
ans.Add(line);
}
else
Thread.Sleep(500);
}
return ans;
}
public void DumpLines() => ReadLines();
public List<string> DoCommand(string cmd) {
sw.Write(cmd);
sw.Write("\r");
sw.Flush();
while (!ssh.DataAvailable)
Thread.Sleep(500);
return ReadLines().SkipWhile(l => l == cmd).ToList();
}
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing) {
if (!disposedValue) {
if (disposing) {
// prevent double dispose
// don't dispose of sr or sw: only disposable resource is ssh
ssh.Dispose();
}
disposedValue = true;
}
}
// This code added to correctly implement the disposable pattern.
public void Dispose() {
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
}
#endregion
}
下面是一个示例函数,它使用该代码和 SSH.Net 从交换机检索配置信息的屏幕副本:
public static void RetrieveConfigFiles(IDFStack idf) {
using (var sshClient = new SshClient(idf.IPAddress, username, password)) {
sshClient.Connect();
using (var ssh = sshClient.CreateExtShellStream("dumb", 120, 80, 0, 0, 200000)) {
ssh.DumpLines();
ssh.DoCommand("no page");
File.WriteAllLines(idf.ConfigPath, ssh.DoCommand("show running-config structured"));
File.WriteAllLines(idf.StatusPath, ssh.DoCommand("show interfaces brief"));
File.WriteAllLines(idf.LLDPPath, ssh.DoCommand("show lldp info remote-device detail"));
}
sshClient.Disconnect();
}
}