TTY 标准输入写入器 PRO

需要 Scripting PRO

表示一个可写的 TTY(终端)标准输入流,用于通过 SSH 建立的伪终端(PTY)或 TTY 会话。该类支持将数据写入远程终端的 stdin,以及动态调整终端窗口大小。

通常由 SSHClient.withPTY()SSHClient.withTTY() 方法返回。


方法

write(data: string): Promise<void>

向远程 TTY 会话的标准输入写入文本数据。

参数:

  • data(字符串): 要发送给远程终端标准输入的字符串,可以包含控制字符(如 "\r" 表示回车,\x03 表示 Ctrl+C)。

返回值:

  • 一个 Promise,在数据成功写入后 resolve。

示例:

1const writer = await ssh.withTTY({
2  onOutput: (text) => {
3    console.log("输出:", text)
4    return true
5  }
6})
7await writer.write("ls -la\n")

changeSize(options: { cols: number; rows: number; pixelWidth: number; pixelHeight: number }): Promise<void>

更改远程终端的窗口尺寸,适用于需要特定终端尺寸的程序(如 vimhtop 等)。

参数:

  • options(对象): 一个包含终端尺寸信息的对象:

    • cols(数字): 终端的字符列数,例如 80。

    • rows(数字): 终端的字符行数,例如 24。

    • pixelWidth(数字): 终端的像素宽度(如果不适用可设为 0)。

    • pixelHeight(数字): 终端的像素高度(如果不适用可设为 0)。

返回值:

  • 一个 Promise,在终端尺寸更改成功后 resolve。

示例:

1await writer.changeSize({
2  cols: 100,
3  rows: 30,
4  pixelWidth: 0,
5  pixelHeight: 0
6})

使用示例

1const ssh = await SSHClient.connect({
2  host: "192.168.1.10",
3  authenticationMethod: SSHAuthenticationMethod.passwordBased("user", "password")
4})
5
6const writer = await ssh.withPTY({
7  term: "xterm",
8  onOutput: (text, isStderr) => {
9    console.log(text)
10    return true
11  }
12})
13
14// 写入命令
15await writer.write("top\n")
16
17// 2 秒后调整终端尺寸
18await new Promise(resolve => setTimeout(resolve, 2000))
19await writer.changeSize({
20  cols: 120,
21  rows: 40,
22  pixelWidth: 0,
23  pixelHeight: 0
24})