CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
rapid7

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: rapid7/metasploit-framework
Path: blob/master/lib/snmp/agent.rb
Views: 11766
1
#
2
# Copyright (c) 2004 David R. Halliday
3
# All rights reserved.
4
#
5
# This SNMP library is free software. Redistribution is permitted under the
6
# same terms and conditions as the standard Ruby distribution. See the
7
# COPYING file in the Ruby distribution for details.
8
#
9
10
require 'snmp'
11
require 'socket'
12
require 'logger'
13
14
module SNMP
15
16
class Agent #:nodoc:all
17
18
def initialize(listen_port=161, max_packet=8000)
19
@log = Logger.new(STDOUT)
20
@log.level = Logger::DEBUG
21
@max_packet = max_packet
22
@socket = UDPSocket.open
23
@socket.bind(nil, listen_port)
24
@mib = MIB::SystemMIB.new
25
end
26
27
def start
28
@log.info "SNMP agent running"
29
loop do
30
begin
31
data, remote_info = @socket.recvfrom(@max_packet)
32
puts "Received #{data.length} bytes"
33
p data
34
message = Message.decode(data)
35
case message.pdu
36
when GetRequest
37
response = message.response
38
response.pdu.varbind_list.each do |v|
39
v.value = @mib.get(v.name)
40
end
41
when SetRequest
42
response = message.response
43
else
44
raise "invalid message #{message.to_s}"
45
end
46
puts "Responding to #{remote_info[3]}:#{remote_info[1]}"
47
encoded_message = response.encode
48
n=@socket.send(encoded_message, 0, remote_info[3], remote_info[1])
49
p encoded_message
50
rescue => e
51
@log.error e
52
shutdown
53
end
54
end
55
end
56
57
def shutdown
58
@log.info "SNMP agent stopping"
59
@socket.close
60
exit
61
end
62
63
alias stop :shutdown
64
65
end
66
67
end
68
69
if $0 == __FILE__
70
agent = SNMP::Agent.new(1061)
71
trap("INT") { agent.shutdown }
72
agent.start
73
end
74
75
76