【问题标题】:Ruby - checking ping status featback with ssh, backtick via ssh?Ruby - 使用 ssh 检查 ping 状态功能,通过 ssh 反引号?
【发布时间】:2015-04-29 06:34:13
【问题描述】:

在我的项目中,我想编写一个脚本来检查我网络中的每个设备是否都在线/可访问。我有一个叫做 pingtest 的方法,它现在可以工作了..

def pingtest(destination)
    system("ping -n 2 #{destination}")
    if $? == 0                                #checking status of the backtick
        puts "\n Ping was successful!"
    else
        close("Device is unreachable. Check the config.txt for the correct IPs.")
        #close() is just print & exit..
    end
end

现在我想通过 ssh 会话与网络中的其他设备进行 ping:

#--------------------------------
require 'net/ssh' 
Net::SSH.start(@ip, @user, :password => @password)
#--------------------------------

@ssh = Ssh.new(@config)
@ssh.cmd("ping -c 3 #{@IP}")

ping 工作正常,但我现在如何使用我的回溯想法来确定它是否成功?
我考虑过使用 sftp 连接..

"ping -c 3 #{@IP} => tmpfile.txt" => 下载 => 检查/比较 => 删除

(或类似的东西)来检查它是否正确,但我不知道它是否正确。是否有可能像以前一样检查成功状态?
我也试过这样的..

result = @ssh.cmd("ping -c 3 #{@IP}")
if result.success? == 0 # and so on..

我几天前开始学习 ruby​​,所以我是新手,期待您的想法来帮助我解决这个问题。

【问题讨论】:

    标签: ruby ssh backticks


    【解决方案1】:

    您可以使用 Net::SSH 远程运行命令,类似于您已经获得的。

    运行命令返回的result 将是写入stdoutstderr 的任何内容。

    您可以使用该返回值的内容来检查它是否成功。

    Net::SSH.start(@ip, @user. password: @password) do |ssh|
      response = ssh.exec! "ping -c 3 #{@other_ip}"
      if response.include? 'Destination Host Unreachable'
        close("Host unreachable. Result was: #{result}")
      else
        puts "\n Ping was successful"
      end
    end
    

    【讨论】:

    • 'block in (mymethod)': undefined local variable or method 'response' for #<Ssh...> <NameError> 好像少了点什么。我尝试了几件事,但现在我认为我只是没有响应方法..我需要实现其他东西吗?
    • 啊是的对不起,重命名了一些变量并忘记了一个。我已经修好了。
    猜你喜欢
    • 2014-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-14
    • 2019-06-17
    • 1970-01-01
    • 2021-04-29
    相关资源
    最近更新 更多