gpt4 book ai didi

ruby - 如何将 SIGINT 发送到 Net::SSH session 中的进程启动?

转载 作者:数据小太阳 更新时间:2023-10-29 07:19:52 26 4
gpt4 key购买 nike

我使用 Net::SSHv2 连接到服务器并在该服务器上启动脚本。到目前为止它正在运行,但我想在脚本运行超过 10 分钟或输出文件太大时中断脚本。收到中断后,脚本将关闭并输出一些统计信息。

我当前的代码如下所示:

File.open(filename, "w") do |f|
Net::SSH.start(host, user, password: password) do |ssh|
ssh.exec! "do_work" do |channel, stream, data|
f << "data"
#break if f.size > 1024 * 1024 * 100 #file size > 100 MB
#channel.send_data "^C" if f.size > 1024 * 1024 * 100 #file size > 100 MB
end
end
end

我尝试了一些其他的方法,为 channel 打开一个 block 并请求一个 shell,但没有成功。

最佳答案

send_data 是正确的方法,但是:

  1. 您需要一个 PTY 以便将控制代码发送到服务器,这也意味着您需要在执行之前打开一个 channel 。
  2. 代码中没有任何内容可以理解脱字符 (^) 后跟大写 C 字符的人类显示约定,意思是“发送键盘 BIOS 生成的字符,当您按 CTRL+C”。您必须发送 ASCII 字符本身,它是 ETX(文本结尾)控制字符,在 C 十六进制转义序列中表示为 \x03
  3. 这在技术上不是 SIGINT 信号 - 它是与 POSIX 信号 IPC 无关的终端中断信号,但 shell 通常将 ETX 解释为“用户想要我向进程发送 SIGINT”——这是你需要 PTY 的主要原因——它指示系统 shell 遵守“键盘生成的控制字符应转换为信号”约定。目前无法通过常见 SSH 实现通过 SSH session 发送实际信号。参见 this answer to a similar (though not Ruby specific) question了解更多详情。

你的代码应该是这样的:

File.open(filename, "w") do |f|
Net::SSH.start(host, user, password: password) do |ssh|
ssh.open_channel do |channel|
channel.request_pty
channel.exec "do_work" do |ch, success|
raise "could not execute command: #{command.inspect}" unless success

channel.on_data do |ch2, data|
f << data
end

#break if f.size > 1024 * 1024 * 100 #file size > 100 MB
channel.send_data "\x03" if f.size > 1024 * 1024 * 100 #file size > 100 MB
end
end.wait
end
end

channel 工作代码或多或少是从session.rb source code中逐字复制的.请参阅它以获取更多信息。

关于ruby - 如何将 SIGINT 发送到 Net::SSH session 中的进程启动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17680589/

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