gpt4 book ai didi

ruby - 使用 Net::SSH 或创建 STDIN 套接字的交互式 SSH session

转载 作者:数据小太阳 更新时间:2023-10-29 08:56:45 24 4
gpt4 key购买 nike

这不是 How to SSH interactive Session 的副本或 Net::SSH interactive terminal scripting. How?Ruby net-ssh interactive response/reply

我正在尝试使用 Net:SSH 编写交互式 SSH 客户端,因为我已经在使用它在目标主机上运行非交互式命令。

我可以直接使用 system "ssh",但它需要将连接设置、代理等转换为 ssh 参数。

问题是将数据从 STDIN 流式传输到 shell channel 。 listen_to 的 Net::SSH 文档显示了当输入来自套接字而不是 STDIN 时如何执行此操作。 $stdinIO.console 不是套接字,因此与 Net::SSH::BufferedIo 不兼容。

有没有办法从 STDIN 创建一个可用于此目的的套接字?或者是否有更好的方法将所有内容从 STDIN 发送到 Net::SSH::Channel 直到 channel 关闭?

这是有效的代码,但速度太慢而无法使用:

require 'net/ssh'
require 'io/console'
require 'io/wait'

Net::SSH.start('localhost', 'root') do |session|
session.open_channel do |channel|
channel.on_data do |_, data|
$stdout.write(data)
end

channel.on_extended_data do |_, data|
$stdout.write(data)
end

channel.request_pty do
channel.send_channel_request "shell"
end

channel.connection.loop do
$stdin.raw do |io|
input = io.readpartial(1024)
channel.send_data(input) unless input.empty?
end
channel.active?
end
end.wait
end

最佳答案

套接字实际上只不过是文件描述符,而且由于 STDIN 也是一个文件描述符,因此尝试一下也没什么坏处。

然而,您想要的是首先将 TTY 置于原始模式以获得交互性。
这段代码似乎工作正常:

begin
system('stty cbreak -echo')

Net::SSH.start(...) do |session|
session.open_channel do |...|
...
session.listen_to(STDIN) { |stdin|
input = stdin.readpartial(1024)
channel.send_data(input) unless input.empty?
}
end.wait
end
ensure
system('stty sane')
end

关于ruby - 使用 Net::SSH 或创建 STDIN 套接字的交互式 SSH session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53006701/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com