1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ruby snmpでbulkwalk

Last updated at Posted at 2019-07-08

Rubyでbulkwalkするスクリプトを組んでみた。

ネットワーク内に存在する大量装置にsnmpbulkwalkするスクリプトを従来Perlで作ってたんだけど、rubyで作り直してみた。
取得回数が限られているbulkwalkであればruby-snmpのExamplesにあったんだけど、同一ツリー内を再帰取得するコードが見当たらなかったので書いておきます。

  • v1の装置があることも考慮し、v1であればwalk、v2cであればget_bulkします。
  • 応答結果は「oid値」「応答値」「タイプ」を配列で回答します
  • ホスト単位にMIB値を連続取得します。ホスト単位にパラレルにしてもいいかも。
  • EndOfMibViewが出たときの例外処理ができていない…ループから抜けるいい方法ないかしら?(r.valueがSNMP::EndOfMiViewになった場合、抜ける必要があります)
snmpbulkwalk.rb
# ! /usr/local/bin/ruby
require 'snmp'

class SNMPWALK
	@@array = Array.new
	def self.bulk(hostname:,community:'public',oid:,max_rep:10)
		SNMP::Manager.open(:Host => hostname , :Community => community) do |manager|
			next_oid = oid
			while next_oid.subtree_of?(oid) do
				response = manager.get_bulk(0,max_rep.to_i,next_oid)
				response.each_varbind do |r|
					next_oid = r.name
					break if !next_oid.subtree_of?(oid)
					@@array.push([r.name.to_a.join('.'),r.value.to_s,r.value.asn1_type])
				end
			end
		end
		return @@array
	end

	def self.walk(hostname:,community:'public',oid:)
		SNMP::Manager.open(:Host => hostname , :Community => community) do |manager|
			next_oid = oid
			manager.walk(next_oid) do |response|
				response.each do |r|
					@@array.push([r.name.to_a.join('.'),r.value.to_s,r.value.asn1_type])
				end
			end
		end
		return @@array
	end
end

#####################################################################################
##  get_mibdata Main
#####################################################################################
['host_a','host_b','host_c'].each do |host|
	snmp_version = "v2c"
	['1.3.6.1.2.1.2.2.1.1','1.3.6.1.2.1.2.2.1.7'].each do |mib|
		oid = SNMP::ObjectId.new(oid) if !oid.kind_of?(SNMP::ObjectId)
		result = ""
		if snmp_version == 'v1'
			result = SNMPWALK.walk(hostname:host,community:'public',oid:mib)
		else
			result = SNMPWALK.bulk(hostname:host,community:'public',oid:mib)
		end
		p result
	end
end

自作コードをQiitaに書いたの初めてなので突っ込み歓迎です。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?