我一直试图让端口转发与Net :: SSH正常工作。根据我的理解,如果我希望能够从同一个Ruby程序使用它,就需要分离出Net :: SSH会话,以便事件处理循环可以真正处理通过连接发送的数据包。然而,这会导致你可以在下面看到的丑陋:如何正确执行Net :: SSH端口转发
#!/usr/bin/env ruby -w
require 'net/ssh'
require 'httparty'
require 'socket'
include Process
log = Logger.new(STDOUT)
log.level = Logger::DEBUG
local_port = 2006
child_socket, parent_socket = Socket.pair(:UNIX, :DGRAM, 0)
maxlen = 1000
hostname = "www.example.com"
pid = fork do
parent_socket.close
Net::SSH.start("hostname", "username") do |session|
session.logger = log
session.logger.sev_threshold=Logger::Severity::DEBUG
session.forward.local(local_port, hostname, 80)
child_socket.send("ready", 0)
pidi = fork do
msg = child_socket.recv(maxlen)
puts "Message from parent was: #{msg}"
exit
end
session.loop do
status = waitpid(pidi, Process::WNOHANG)
puts "Status: #{status.inspect}"
status.nil?
end
end
end
child_socket.close
puts "Message from child: #{parent_socket.recv(maxlen)}"
resp = HTTParty.post("http://localhost:#{local_port}/", :headers => { "Host" => hostname })
# the write cannot be the last statement, otherwise the child pid could end up
# not receiving it
parent_socket.write("done")
puts resp.inspect
有人能告诉我一个更优雅/更好的工作解决了这个?
这很不错。我首先想到的是,这个互斥量同步0.01秒的短暂等待时间会引入很多CPU开销,但并不像我想象的那么糟糕(我的MBP的持续背景只有不到2%)。当然,这也可以通过增加ssh进程等待时间来稍微调整,以避免响应中可预测性的轻微损失。 – HerbCSO
PS:注意[SSH :: Net的文档]中的警告(http://net-ssh.github.io/ssh/v2/api/classes/Net/SSH/Connection/Session.html#M000088):don' t设置进程轮询时间为0,那么你会吃掉大量的CPU。 ] – HerbCSO