经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » ASP.net » 查看文章
Web SSH 的原理与在 ASP.NET Core SignalR 中的实现
来源:cnblogs  作者:Aoba_xu  时间:2023/11/1 9:02:48  对本文有异议

前言

有个项目,需要在前端有个管理终端可以 SSH 到主控机的终端,如果不考虑用户使用 vim 等需要在控制台内现实界面的软件的话,其实使用 Process 类型去启动相应程序就够了。而这次的需求则需要考虑用户会做相关设置。

原理

这里用到的原理是伪终端。伪终端(pseudo terminal)是现代操作系统的一个功能,他会模拟一对输入输出设备来模拟终端环境去执行相应的进程。伪终端通常会给相应的进程提供例如环境变量或文件等来告知他在终端中运行,这样像 vim 这样的程序可以在最后一行输出命令菜单或者像 npm / pip 这样的程序可以打印炫酷的进度条。通常在我们直接创建子进程的时候,在 Linux 上系统自带了 openpty 方法可以打开伪终端,而在 Windows 上则等到 Windows Terminal 推出后才出现了真正的系统级伪终端。下面付一张来自微软博客的伪终端原理图,Linux 上的原理与之类似。

伪终端原理图

基本设计

建立连接与监听终端输出

监听前端输入

graph TD; A[终端窗口收到键盘事件] --> B[SignalR 发送请求]; B --> C[后台转发到对应终端]

超时与关闭

graph TD; A[当 SignalR 发送断开连接或终端超时] --> B[关闭终端进程];

依赖库

portable_pty

这里用到这个 Rust 库来建立终端,这个库是一个独立的进程,每次建立连接都会运行。这里当初考虑过直接在 ASP.NET Core 应用里调用 vs-pty(微软开发的,用在 vs 里的库,可以直接在 vs 安装位置复制一份),但是 vs-pty 因为种种原因在 .NET 7 + Ubuntu 22.04 的环境下运行不起来故放弃了。

xterm.js

这个是前端展示终端界面用的库,据说 vs code 也在用这个库,虽然文档不多,但是用起来真的很简单。

SignalR

这个不多说了,咱 .NET 系列 Web 实时通信选他就没错。

代码

废话不多讲了,咱还是直接看代码吧,这里代码还是比较长的,我节选了一些必要的代码。具体 SignalR 之类的配置,还请读者自行参考微软官方文档。

  1. main.rs 这个 Rust 代码用于建立伪终端并和 .NET 服务通信,这里使用了最简单的 UDP 方式通信。
  1. use portable_pty::{self, native_pty_system, CommandBuilder, PtySize};
  2. use std::{io::prelude::*, sync::Arc};
  3. use tokio::net::UdpSocket;
  4. #[tokio::main(flavor = "multi_thread", worker_threads = 4)]
  5. async fn main() -> Result<(), Box<dyn std::error::Error>> {
  6. let args = std::env::args().collect::<Vec<_>>();
  7. // 启动一个终端
  8. let pty_pair = native_pty_system().openpty(PtySize {
  9. rows: args.get(2).ok_or("NoNumber")?.parse()?,
  10. cols: args.get(3).ok_or("NoNumber")?.parse()?,
  11. pixel_width: 0,
  12. pixel_height: 0,
  13. })?;
  14. // 执行传进来的命令
  15. let mut cmd = CommandBuilder::new(args.get(4).unwrap_or(&"bash".to_string()));
  16. if args.len() > 5 {
  17. cmd.args(&args[5..]);
  18. }
  19. let mut proc = pty_pair.slave.spawn_command(cmd)?;
  20. // 绑定输入输出
  21. let mut reader = pty_pair.master.try_clone_reader()?;
  22. let mut writer = pty_pair.master.take_writer()?;
  23. // 绑定网络
  24. let main_socket = Arc::new(UdpSocket::bind("localhost:0").await?);
  25. let recv_socket = main_socket.clone();
  26. let send_socket = main_socket.clone();
  27. let resize_socket = UdpSocket::bind("localhost:0").await?;
  28. // 连接到主服务后发送地址
  29. main_socket
  30. .connect(args.get(1).ok_or("NoSuchAddr")?)
  31. .await?;
  32. main_socket
  33. .send(&serde_json::to_vec(&ClientAddr {
  34. main: main_socket.local_addr()?.to_string(),
  35. resize: resize_socket.local_addr()?.to_string(),
  36. })?)
  37. .await?;
  38. // 读取终端数据并发送
  39. let read = tokio::spawn(async move {
  40. loop {
  41. let mut buf = [0; 1024];
  42. let n = reader.read(&mut buf).unwrap();
  43. if n == 0 {
  44. continue;
  45. }
  46. println!("{:?}", &buf[..n]);
  47. send_socket.send(&buf[..n]).await.unwrap();
  48. }
  49. });
  50. // 接收数据并写入终端
  51. let write = tokio::spawn(async move {
  52. loop {
  53. let mut buf = [0; 1024];
  54. let n = recv_socket.recv(&mut buf).await.unwrap();
  55. if n == 0 {
  56. continue;
  57. }
  58. println!("{:?}", &buf[..n]);
  59. writer.write_all(&buf[..n]).unwrap();
  60. }
  61. });
  62. // 接收调整窗口大小的数据
  63. let resize = tokio::spawn(async move {
  64. let mut buf = [0; 1024];
  65. loop {
  66. let n = resize_socket.recv(&mut buf).await.unwrap();
  67. if n == 0 {
  68. continue;
  69. }
  70. let size: WinSize = serde_json::from_slice(buf[..n].as_ref()).unwrap();
  71. pty_pair
  72. .master
  73. .resize(PtySize {
  74. rows: size.rows,
  75. cols: size.cols,
  76. pixel_width: 0,
  77. pixel_height: 0,
  78. })
  79. .unwrap();
  80. }
  81. });
  82. // 等待进程结束
  83. let result = proc.wait()?;
  84. write.abort();
  85. read.abort();
  86. resize.abort();
  87. if 0 == result.exit_code() {
  88. std::process::exit(result.exit_code() as i32);
  89. }
  90. return Ok(());
  91. }
  92. /// 窗口大小
  93. #[derive(serde::Deserialize)]
  94. struct WinSize {
  95. /// 行数
  96. rows: u16,
  97. /// 列数
  98. cols: u16,
  99. }
  100. /// 客户端地址
  101. #[derive(serde::Serialize)]
  102. struct ClientAddr {
  103. /// 主要地址
  104. main: String,
  105. /// 调整窗口大小地址
  106. resize: String,
  107. }
  1. SshPtyConnection.cs 这个代码用于维持一个后台运行的 Rust 进程,并管理他的双向通信。
  1. public class SshPtyConnection : IDisposable
  2. {
  3. /// <summary>
  4. /// 客户端地址
  5. /// </summary>
  6. private class ClientEndPoint
  7. {
  8. public required string Main { get; set; }
  9. public required string Resize { get; set; }
  10. }
  11. /// <summary>
  12. /// 窗口大小
  13. /// </summary>
  14. private class WinSize
  15. {
  16. public int Cols { get; set; }
  17. public int Rows { get; set; }
  18. }
  19. /// <summary>
  20. /// SignalR 上下文
  21. /// </summary>
  22. private readonly IHubContext<SshHub> _hubContext;
  23. /// <summary>
  24. /// 日志记录器
  25. /// </summary>
  26. private readonly ILogger<SshPtyConnection> _logger;
  27. /// <summary>
  28. /// UDP 客户端
  29. /// </summary>
  30. private readonly UdpClient udpClient;
  31. /// <summary>
  32. /// 最后活动时间
  33. /// </summary>
  34. private DateTime lastActivity = DateTime.UtcNow;
  35. /// <summary>
  36. /// 是否已释放
  37. /// </summary>
  38. private bool disposedValue;
  39. /// <summary>
  40. /// 是否已释放
  41. /// </summary>
  42. public bool IsDisposed => disposedValue;
  43. /// <summary>
  44. /// 最后活动时间
  45. /// </summary>
  46. public DateTime LastActivity => lastActivity;
  47. /// <summary>
  48. /// 取消令牌
  49. /// </summary>
  50. public CancellationTokenSource CancellationTokenSource { get; } = new CancellationTokenSource();
  51. /// <summary>
  52. /// 窗口大小
  53. /// </summary>
  54. public event EventHandler<EventArgs> Closed = delegate { };
  55. /// <summary>
  56. /// 构造函数
  57. /// </summary>
  58. /// <param name="hubContext"></param>
  59. /// <param name="logger"></param>
  60. /// <exception cref="ArgumentNullException"></exception>
  61. public SshPtyConnection(IHubContext<SshHub> hubContext, ILogger<SshPtyConnection> logger)
  62. {
  63. _hubContext = hubContext ?? throw new ArgumentNullException(nameof(hubContext));
  64. _logger = logger ?? throw new ArgumentNullException(nameof(logger));
  65. lastActivity = DateTime.Now;
  66. udpClient = new(IPEndPoint.Parse("127.0.0.1:0"));
  67. }
  68. /// <summary>
  69. /// 开始监听
  70. /// </summary>
  71. /// <param name="connectionId">连接 ID</param>
  72. /// <param name="username">用户名</param>
  73. /// <param name="height">行数</param>
  74. /// <param name="width">列数</param>
  75. public async void StartAsync(string connectionId, string username, int height, int width)
  76. {
  77. var token = CancellationTokenSource.Token;
  78. _logger.LogInformation("process starting");
  79. // 启动进程
  80. using var process = Process.Start(new ProcessStartInfo
  81. {
  82. FileName = OperatingSystem.IsOSPlatform("windows") ? "PtyWrapper.exe" : "pty-wrapper",
  83. // 这里用了 su -l username,因为程序直接部署在主控机的 root 下,所以不需要 ssh 只需要切换用户即可,如果程序部署在其他机器上,需要使用 ssh
  84. ArgumentList = { udpClient.Client.LocalEndPoint!.ToString() ?? "127.0.0.1:0", height.ToString(), width.ToString(), "su", "-l", username }
  85. });
  86. // 接收客户端地址
  87. var result = await udpClient.ReceiveAsync();
  88. var clientEndPoint = await JsonSerializer.DeserializeAsync<ClientEndPoint>(new MemoryStream(result.Buffer), new JsonSerializerOptions
  89. {
  90. PropertyNameCaseInsensitive = true
  91. });
  92. if (clientEndPoint == null)
  93. {
  94. CancellationTokenSource.Cancel();
  95. return;
  96. }
  97. process!.Exited += (_, _) => CancellationTokenSource.Cancel();
  98. var remoteEndPoint = IPEndPoint.Parse(clientEndPoint.Main);
  99. udpClient.Connect(remoteEndPoint);
  100. var stringBuilder = new StringBuilder();
  101. // 接收客户端数据,并发送到 SignalR,直到客户端断开连接或者超时 10 分钟
  102. while (!token.IsCancellationRequested && lastActivity.AddMinutes(10) > DateTime.Now && !(process?.HasExited ?? false))
  103. {
  104. try
  105. {
  106. lastActivity = DateTime.Now;
  107. var buffer = await udpClient.ReceiveAsync(token);
  108. await _hubContext.Clients.Client(connectionId).SendAsync("WriteDataAsync", Encoding.UTF8.GetString(buffer.Buffer));
  109. stringBuilder.Clear();
  110. }
  111. catch (Exception e)
  112. {
  113. _logger.LogError(e, "ConnectionId: {ConnectionId} Unable to read data and send message.", connectionId);
  114. break;
  115. }
  116. }
  117. // 如果客户端断开连接或者超时 10 分钟,关闭进程
  118. if (process?.HasExited ?? false) process?.Kill();
  119. if (lastActivity.AddMinutes(10) < DateTime.Now)
  120. {
  121. _logger.LogInformation("ConnectionId: {ConnectionId} Pty session has been closed because of inactivity.", connectionId);
  122. try
  123. {
  124. await _hubContext.Clients.Client(connectionId).SendAsync("WriteErrorAsync", "InactiveTimeTooLong");
  125. }
  126. catch (Exception e)
  127. {
  128. _logger.LogError(e, "ConnectionId: {ConnectionId} Unable to send message.", connectionId);
  129. }
  130. }
  131. if (token.IsCancellationRequested)
  132. {
  133. _logger.LogInformation("ConnectionId: {ConnectionId} Pty session has been closed because of session closed.", connectionId);
  134. try
  135. {
  136. await _hubContext.Clients.Client(connectionId).SendAsync("WriteErrorAsync", "SessionClosed");
  137. }
  138. catch (Exception e)
  139. {
  140. _logger.LogError(e, "ConnectionId: {ConnectionId} Unable to send message.", connectionId);
  141. }
  142. }
  143. Dispose();
  144. }
  145. /// <summary>
  146. /// 接收 SignalR 数据,并发送到客户端
  147. /// </summary>
  148. /// <param name="data">数据</param>
  149. /// <returns></returns>
  150. /// <exception cref="AppException"></exception>
  151. public async Task WriteDataAsync(string data)
  152. {
  153. if (disposedValue)
  154. {
  155. throw new AppException("SessionClosed");
  156. }
  157. try
  158. {
  159. lastActivity = DateTime.Now;
  160. await udpClient.SendAsync(Encoding.UTF8.GetBytes(data));
  161. }
  162. catch (Exception e)
  163. {
  164. CancellationTokenSource.Cancel();
  165. Dispose();
  166. throw new AppException("SessionClosed", e);
  167. }
  168. }
  169. /// <summary>
  170. /// 回收资源
  171. /// </summary>
  172. /// <param name="disposing"></param>
  173. protected virtual void Dispose(bool disposing)
  174. {
  175. if (!disposedValue)
  176. {
  177. if (disposing)
  178. {
  179. CancellationTokenSource.Cancel();
  180. udpClient.Dispose();
  181. }
  182. disposedValue = true;
  183. Closed(this, new EventArgs());
  184. }
  185. }
  186. public void Dispose()
  187. {
  188. Dispose(disposing: true);
  189. GC.SuppressFinalize(this);
  190. }
  191. }
  1. SshService 这段代码用于管理 SshPtyConnection 和 SignalR 客户端连接之间的关系
  1. public class SshService : IDisposable
  2. {
  3. private bool disposedValue;
  4. private readonly IHubContext<SshHub> _hubContext;
  5. private readonly ILoggerFactory _loggerFactory;
  6. private Dictionary<string, SshPtyConnection> _connections;
  7. public SshService(IHubContext<SshHub> hubContext, ILoggerFactory loggerFactory)
  8. {
  9. _hubContext = hubContext ?? throw new ArgumentNullException(nameof(hubContext));
  10. _connections = new Dictionary<string, SshPtyConnection>();
  11. _loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
  12. }
  13. /// <summary>
  14. /// 创建终端连接
  15. /// </summary>
  16. /// <param name="connectionId">连接 ID</param>
  17. /// <param name="username">用户名</param>
  18. /// <param name="height">行数</param>
  19. /// <param name="width">列数</param>
  20. /// <returns></returns>
  21. /// <exception cref="InvalidOperationException"></exception>
  22. public Task CreateConnectionAsync(string connectionId, string username, int height, int width)
  23. {
  24. if (_connections.ContainsKey(connectionId))
  25. throw new InvalidOperationException();
  26. var connection = new SshPtyConnection(_hubContext, _loggerFactory.CreateLogger<SshPtyConnection>());
  27. connection.Closed += (sender, args) =>
  28. {
  29. _hubContext.Clients.Client(connectionId).SendAsync("WriteErrorAsync", "SessionClosed");
  30. _connections.Remove(connectionId);
  31. };
  32. _connections.Add(connectionId, connection);
  33. // 运行一个后台线程
  34. connection.StartAsync(connectionId, username, height, width);
  35. return Task.CompletedTask;
  36. }
  37. /// <summary>
  38. /// 写入数据
  39. /// </summary>
  40. /// <param name="connectionId">连接 ID</param>
  41. /// <param name="data">数据</param>
  42. /// <exception cref="AppException"></exception>
  43. public async Task ReadDataAsync(string connectionId, string data)
  44. {
  45. if (_connections.TryGetValue(connectionId, out var connection))
  46. {
  47. await connection.WriteDataAsync(data);
  48. }
  49. else
  50. throw new AppException("SessionClosed");
  51. }
  52. /// <summary>
  53. /// 关闭连接
  54. /// </summary>
  55. /// <param name="connectionId">连接 ID</param>
  56. /// <exception cref="AppException"></exception>
  57. public Task CloseConnectionAsync(string connectionId)
  58. {
  59. if (_connections.TryGetValue(connectionId, out var connection))
  60. {
  61. connection.Dispose();
  62. }
  63. else
  64. throw new AppException("SessionClosed");
  65. return Task.CompletedTask;
  66. }
  67. /// <summary>
  68. /// 回收资源
  69. /// </summary>
  70. /// <param name="disposing"></param>
  71. protected virtual void Dispose(bool disposing)
  72. {
  73. if (!disposedValue)
  74. {
  75. if (disposing)
  76. {
  77. foreach (var item in _connections.Values)
  78. {
  79. item.Dispose();
  80. }
  81. }
  82. disposedValue = true;
  83. }
  84. }
  85. public void Dispose()
  86. {
  87. Dispose(disposing: true);
  88. GC.SuppressFinalize(this);
  89. }
  90. }
  1. WebSsh.vue 这段代码是使用 vue 展示终端窗口的代码
  1. <script setup lang="ts">
  2. import { onMounted, ref } from 'vue';
  3. import { Terminal } from 'xterm';
  4. import { FitAddon } from 'xterm-addon-fit';
  5. import { WebLinksAddon } from 'xterm-addon-web-links';
  6. import { SearchAddon } from 'xterm-addon-search';
  7. import { WebglAddon } from 'xterm-addon-webgl';
  8. import * as signalR from '@microsoft/signalr';
  9. import 'xterm/css/xterm.css';
  10. const termRef = ref<HTMLElement | null>(null);
  11. // 创建 xterm 终端
  12. const term = new Terminal();
  13. // 定义 SignalR 客户端
  14. const connection = new signalR.HubConnectionBuilder()
  15. .withUrl('/hubs/ssh', {
  16. accessTokenFactory: () => localStorage.getItem('token'),
  17. } as any)
  18. .build();
  19. let isClosed = false;
  20. // 监听键盘事件并发送到后端
  21. term.onData((data) => {
  22. if (isClosed) {
  23. return;
  24. }
  25. connection.invoke('ReadDataAsync', data).then((result) => {
  26. if (result.code == 400) {
  27. isClosed = true;
  28. term.write('SessionClosed');
  29. }
  30. });
  31. });
  32. // 监听后端数据回传
  33. connection.on('WriteDataAsync', (data) => {
  34. term.write(data);
  35. });
  36. // 监听后端终端关闭
  37. connection.on('WriteErrorAsync', () => {
  38. isClosed = true;
  39. term.write('SessionClosed');
  40. });
  41. // 加载插件
  42. const fit = new FitAddon();
  43. term.loadAddon(fit);
  44. term.loadAddon(new WebLinksAddon());
  45. term.loadAddon(new SearchAddon());
  46. term.loadAddon(new WebglAddon());
  47. onMounted(async () => {
  48. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  49. term.open(termRef.value!);
  50. fit.fit();
  51. // 启动 SignalR 客户端
  52. await connection.start();
  53. // 创建终端
  54. connection.invoke('CreateNewTerminalAsync', term.rows, term.cols);
  55. });
  56. </script>
  57. <template>
  58. <div ref="termRef" class="xTerm"></div>
  59. </template>
  60. <style scoped>
  61. </style>
  1. SshHub.cs 这个文件是 SignalR 的 Hub 文件,用来做监听的。
  1. [Authorize]
  2. public class SshHub : Hub<ISshHubClient>
  3. {
  4. private readonly SshService _sshService;
  5. private readonly ILogger<SshHub> _logger;
  6. public SshHub(SshService sshService, ILogger<SshHub> logger)
  7. {
  8. _sshService = sshService ?? throw new ArgumentNullException(nameof(sshService));
  9. _logger = logger ?? throw new ArgumentNullException(nameof(logger));
  10. }
  11. /// <summary>
  12. /// 创建一个新的终端
  13. /// </summary>
  14. /// <param name="height"></param>
  15. /// <param name="width"></param>
  16. /// <returns></returns>
  17. public async Task<BaseResponse> CreateNewTerminalAsync(int height = 24, int width = 80)
  18. {
  19. try
  20. {
  21. var username = Context.User?.FindFirst("preferred_username")?.Value;
  22. if (username == null)
  23. {
  24. return new BaseResponse
  25. {
  26. Code = 401,
  27. Message = "NoUsername"
  28. };
  29. }
  30. if (!Context.User?.IsInRole("user") ?? false)
  31. {
  32. username = "root";
  33. }
  34. _logger.LogInformation($"{username}");
  35. await _sshService.CreateConnectionAsync(Context.ConnectionId, username, height, width);
  36. return new BaseResponse();
  37. }
  38. catch (InvalidOperationException)
  39. {
  40. return new BaseResponse() { Code = 500, Message = "TerminalAlreadyExist" };
  41. }
  42. catch (Exception e)
  43. {
  44. _logger.LogError(e, "ConnectionId: {ConnectionId} No such pty session.", Context.ConnectionId);
  45. return new BaseResponse() { Code = 500, Message = "UnableToCreateTerminal" };
  46. }
  47. }
  48. /// <summary>
  49. /// 读取输入数据
  50. /// </summary>
  51. /// <param name="data"></param>
  52. /// <returns></returns>
  53. public async Task<BaseResponse> ReadDataAsync(string data)
  54. {
  55. try
  56. {
  57. await _sshService.ReadDataAsync(Context.ConnectionId, data);
  58. return new BaseResponse();
  59. }
  60. catch (Exception e)
  61. {
  62. _logger.LogError(e, "ConnectionId: {ConnectionId} No such pty session.", Context.ConnectionId);
  63. return new BaseResponse { Message = "NoSuchSeesion", Code = 400 };
  64. }
  65. }
  66. }
  67. /// <summary>
  68. /// 客户端接口
  69. /// </summary>
  70. public interface ISshHubClient
  71. {
  72. /// <summary>
  73. /// 写入输出数据
  74. /// </summary>
  75. /// <param name="data"></param>
  76. /// <returns></returns>
  77. Task WriteDataAsync(string data);
  78. /// <summary>
  79. /// 写入错误数据
  80. /// </summary>
  81. /// <param name="data"></param>
  82. /// <returns></returns>
  83. Task WriteErrorAsync(string data);
  84. }

参考文献

  1. Windows Command-Line: Introducing the Windows Pseudo Console (ConPTY)
  2. portable_pty - Rust
  3. xterm.js
  4. 教程:使用 TypeScript 和 Webpack 开始使用 ASP.NET Core SignalR

原文链接:https://www.cnblogs.com/aobaxu/p/17799346.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号