2016-11-08 77 views
1

我運行紅寶石1.9。我有這個代碼,它是從這兩個/usr/sbin/storcli /c0/bbu show j & /usr/sbin/storcli /c0/cv show j命令中提取出StatusState的值。處理空值與JSON返回

#!/usr/bin/ruby 
require 'json' 

output_bbu = %x{/usr/sbin/storcli /c0/bbu show j} 
output_cv = %x{/usr/sbin/storcli /c0/cv show j} 

begin 
     j = JSON.parse(output_bbu) 
     k = JSON.parse(output_cv) 
     result = j["Controllers"][0]["Command Status"]["Status"] 

     ### I'm not sure how to get the value of "State" and store it in "status" variable. 

     status = k["Controllers"][0]["Response Data"]["Cachevault_Info"][0]["State"] 
     status = j["Controllers"][0]["Response Data"]["BBU_Info"][0]["State"] 

     ### 
rescue Exception => e 
     puts "CRITICAL: error reading BBU status: #{e}" 
     exit 2 
end 

if result != 'Success' 
     puts "CRITICAL: command not successful, result: #{result}" 
     exit 2 
end 

問題

其中兩個命令storcli /c0/cv show jstorcli /c0/bbu show j在 「狀態」 返回空值的變量和腳本失敗,錯誤

未定義的方法`[]」爲無:NilClass

storcli /c0/cv show j co uld返回「State」的零值或storcli /c0/bbu show j可返回零。所以我想要做的是將「狀態」的值存儲在變量「狀態」中。命令

示例輸出,

$ storcli /c0/cv show j 

{ 
"Controllers":[ 
{ 
     "Command Status" : { 
       "Controller" : 0, 
       "Status" : "Success", 
       "Description" : "None" 
     }, 
     "Response Data" : { 
       "Cachevault_Info" : [ 
         { 
           "Model" : "CVPM02", 
           "State" : "Optimal", 
           "Temp" : "35C", 
           "Mode" : "-", 
           "MfgDate" : "2013/09/17" 
         } 
       ] 
     } 
} 
] 
} 

看,這裏它返回「狀態」爲「最佳」的價值,所以我想它的值存儲在變量「的地位。」

零的示例輸出,

$ storcli /c0/bbu show j 

{ 
"Controllers":[ 
{ 
     "Command Status" : { 
       "Controller" : 0, 
       "Status" : "Failure", 
       "Description" : "None", 
       "Detailed Status" : [ 
         { 
           "Ctrl" : 0, 
           "Status" : "Failed", 
           "Property" : "-", 
           "ErrMsg" : "use /cx/cv", 
           "ErrCd" : 1001 
         } 
       ] 
     } 
} 
] 
} 

回答

1

既然你不是從一個命令得到一個「響應數據」,您可以使用下面的

status = k["Controllers"][0] 
      .fetch(["Response Data"], {}) 
      .fetch(["Cachevault_Info"], {}) 
      .fetch([0], {})["Status"] 
status ||= j["Controllers"][0]["Response Data"]["BBU_Info"][0]["State"] 

隨着||=,如果結果from status = knil它會設置爲status = j

+0

我只關心'State'的值而不管命令。不是「詳細狀態」中的「狀態」。 – Rahul

+0

如果沒有來自bbu的「狀態」,那麼使用'storcli/c0/cv show j'命令並將該值存儲在「狀態」 – Rahul

+0

感謝您的更新,但我仍然得到'CRITICAL:讀取BBU狀態時出錯:未定義的方法[]爲零:NilClass' – Rahul