我目前正在使用 SSH.NET 进行终端仿真。使用当前列/行创建 SshClient 和 ShellStream 可以正常工作。
但是当我更改终端尺寸的大小(如 Putty)时,我找不到将新列/行发送到服务器的方法。
我看到的唯一方法是关闭 shellstream 并创建一个新的。有没有更好的方法将新的“布局”发送到服务器?
提前致谢:-)
经过几天的调查,我最终在 ShellStream.cs 中实现了一种新方法:
/// <summary>
/// Sends a "window-change" request.
/// </summary>
/// <param name="columns">The terminal width in columns.</param>
/// <param name="rows">The terminal width in rows.</param>
/// <param name="width">The terminal height in pixels.</param>
/// <param name="height">The terminal height in pixels.</param>
public void SendWindowChangeRequest(uint columns, uint rows, uint width, uint height)
{
if (_channel == null)
{
throw new ObjectDisposedException("ShellStream");
}
_channel.SendWindowChangeRequest(columns, rows, width, height);
}
问题就解决了。现在我可以调用“SendWindowChangeRequest(...)”并且服务器端 shell 窗口已更新:-)
不确定为什么 Renci 的实现中缺少此功能。也许还有另一种方法...
为了解决这个问题,我创建了一个扩展方法,通过反射成功调用内部 ChannelSession 类的 SendWindowChangeRequest 方法(ShellStream 有一个名为 _channel 的私有属性)。
using System.Reflection;
using Renci.SshNet;
namespace YourFavNamespace;
public static class ShellStreamExtension
{
public static void SendWindowChangeRequest(this ShellStream stream, uint cols, uint rows, uint width, uint height)
{
// The shell stream is a private class, so we need
// to use reflection to access its private fields and methods
// The strategy is to get the _channel field from the ShellStream, and then
// get the SendWindowChangeRequest method from the _channel field
// for submitting low level requests to the shell stream to change its window size at runtime
// get _channel from ShellStream by reflection
var _channel =
stream.GetType().GetField("_channel",
BindingFlags.NonPublic | BindingFlags.Instance)?.GetValue(stream);
// get SendWindowChangeRequest method from _channel by reflection
var method =
_channel?.GetType().GetMethod("SendWindowChangeRequest",
BindingFlags.Public | BindingFlags.Instance);
// invoke SendWindowChangeRequest method for change cols, rows, width and height of the shell stream
method?.Invoke(_channel, new object[] { cols, rows, width, height });
}
}