SNMP、rrdtool


SNMP原理和實戰

SNMP是什么?

snmp(Simple Network Management Protocal, 簡單網絡管理協議)在架構體系的監控子系統中將扮演重要角色。大體上,其基本原理是,在每一個被監控的主機或節點上 (如交換機)都運行了一個 agent,用來收集這個節點的所有相關的信息,同時監聽 snmp 的 port,也就是 UDP 161,並從這個端口接收來自監控主機的指令(查詢和設置)。

如果安裝 net-snmp,被監控主機需要安裝 net-snmp(包含了 snmpd 這個 agent),而監控端需要安裝 net-snmp-utils,若接受被監控端通過trap-communicate發來的信息的話,則需要安裝net-snmp,並啟用trap服務。如果自行編譯,需要 beecrypt(libbeecrypt)和 elf(libraryelf)的庫。

Brief description of the MIB-II groups

SNMP Operations

# Each of the following SNMP operations has a standard PDU format
# snpm 報文
get # 獲取一個指定的OID(object identifer)的信息
getnext # 獲取某一個節點下的所有子節點的指標信息(節點下必須到指標)
getbulk(SNMPV2 and SNMPV3)  # 獲取某一節點下所有子節點下全部信息(節點下是另一個節點,比getnext獲取的范圍更廣)
set # 向控制端發起控制指令,比如:向控制端發起關機指令。
getresponse # 客戶端發起響應的命令
trap # trap端發起的命令
notification(SNMPv2 and SNMPv3)
inform(SNMPv2 and SNMPv3)
report(SNMPv2 and SNMPv3)

Host Management Revisited

# Managing your hosts is an important part of network management 
# The Host Resources MIB defines the follwing seven groups:

host	OBJECT IDENTIFIER ::={mib-2 25}
hrSystem	OBJECT IDENTIFIER ::={host 1}
hrStorage	OBJECT IDENTIFIER ::={host 2}
hrDevice	OBJECT IDENTIFIER ::={ host 3}
hrSWRun		OBJECT IDENTIFIER ::={ host 4}  # 獲取的是操作系統的版本號
hrSWRunPerf	 OBJECT IDENTIFIER ::={ host 5}  # 系統的性能
hrSWInstalled OBJECT IDENTIFIER ::={ host 6}  # 在操作系統上裝了哪些軟件

The host OID is 1.3.6.1.2.1.25
(iso.org.dod.internet.mgmt.mib-2.host)
The hrSystem(1.3.6.1.2.1.25.1)group defines objects that pertain to the system itself.These objects inclede uptime system date,system users,and system processes

The hrDevice(1.3.6.1.2.1.25.3) and hrStorage(1.3.6..1.2.1.25.2) groups define objects pertaining to filesystems and system storage,such as total system memory,disk utilization,and CPU nonidle percentage.

The hrSWRun(1.3.6..1.2.1.25.4),hrSWRunPerf(1.3.6.1.2.1.25.5),and hrSWInstalled(1.3.6.1.2.1.25.6) groups define objects that represent various aspects of software running or installed on the system 
	From these groups,you can determine what operating system is running on the host,as well as what programs the host is currently running
	The hrSWInstalled group can be used to track which software packages are installed


net-snmp(Agent):主要用在被監控端
net-snmp-utils(NMS:command):監控端所用到的命令都在這個包,比如: get set

如果我們要接收被監控端的通過trap community發來的信息的話,我們的監控端就必須要安裝 net-snmp包,並啟用net-snmp包中的/usr/lib/systemd/system/snmptrapd.service 服務


yum install -y net-snmp net-snmp-utils

net-snmp包文件介紹:
	/etc/snmp/snmpd.conf 為agent用的
	/etc/sysconfig/snmpd
	/etc/sysconfig/snmptrapd


snmpwalk -v 1 -c public localhost host
cd /usr/share/snmp/mibs

snmpwalk -v 1 -c public localhost HOST-RESOURCES-MIB::hrSystemUptime.0

# 配置mib庫,以/usr/share/snmp/mibs/SNMPv2-MIB.txt庫為例
less SNMPv2-MIB.txt  # 得到對應的OID號為6     mib-2 6
vim /etc/snmp/snmpd.conf
	view    systemview    included   .1.3.6.1.2.1.6
systemctl restart snmpd
snmpwalk -v 2c -c public localhost tcp

snmpwalk -v 2c -c public localhost tcp | grep established | wc -l



配置允許哪些主機來訪問

vim /etc/snmp/snmpd.conf

#       sec.name       source       community 
com2sec notConfigUser  127.0.0.1    mypublic   # community盡量配置的復雜一點,不要讓別人知道。 此時只允許本地訪問


# 配置允許某一個網段來訪問
#       sec.name       source       	community 
com2sec notConfigUser  192.168.1.0/24     mypublic 
 

 

p配置主機允許某一個網段訪問

snmpnetstat

snmpnetstat -v 2c -c mypublic -Ca -Cp tcp 192.168.1.11  # 獲取指定主機上建立的TCP鏈接
snmpnetstat -v 2c -c mypublic -Can -Cp tcp 192.168.1.11 # 以數字的方式顯示IP地址,不然還要反解成主機名


RRDTool(RoundRobinDatabaseTool)

環狀數據庫官方文檔:https://oss.oetiker.ch/rrdtool/doc/rrdgraph_graph.en.html

RRDTool 是一套監測工具,可用於存儲和展示被監測對象隨時間的變化情況。比如,我們在 Windows 電腦上常見的內存和 CPU 使用情況。

RRD 全稱是 Round Robin Database ,即「環型數據庫」。顧名思義,它是一種循環使用存儲空間的數據庫,適用於存儲和時間序列相關的數據。
RRD 數據庫在被創建的時候就已經定義好了大小,當空間存儲滿了以后,又從頭開始覆蓋舊的數據,所以和其他線性增長的數據庫不同,RRD 的大小可控且不用維護。

Rrdtool是環形數據庫工具,存儲和讀取的是環形數據庫,表現是后綴為.rrd的二進制文件。要大概理解啥是環形數據庫,我對它的理解就是把它想象成圓形的時鍾,隨着時間推移,不斷往里寫數據,同時有個標記指向當前數據記錄的最新位置,就像時鍾上的指針指示當前時間一樣。又因為它是圓形的,無始無終,可以一直往里寫數據,只是歷史數據會被覆蓋掉,所以,有時它又被叫做時序結構數據庫。

rrdtool的三個常用命令create、update、graph

# Create命令格式: set up a new round robin database
rrdtool create filename [--start|-b start time] [--step|-s step] [--template|-t template-file] [--source|-r source-file] [--no-overwrite|-O] [--daemon|-d address] [DS:ds-name[=mapped-ds-name[[source-index]]]:DST:dst arguments] [RRA:CF:cf arguments]

--start|-b start time (default:now-10s)
--step|-s step (default:300 seconds)
RRA:round robin archive,輪轉歸檔信息
CF:consolidation function,聚合函數

DS:ds-name:DST:dst arguments
	A single RRD can accept input form several data sources (DS)
	ds-name is the name you will use to reference this particular data source from an RRD
		A ds-name must be 1 to 19 characters long in the characters [a-zA-Z0-9]
	DST defines the Data Source Type
		For GAUGE,COUNTER,DERIVE,and ABSOLUTE the format for a data source entry is:
			DS:ds-name:GUAGE | COUNTER | DERIVE | ABSOLUTE:heartbeat:min:max # 不知道min,max;可以定義為:U:U,表示不限定值得范圍
				heartbeat:當數據沒按照我們指定的時間到來,比如每5s接收一個數據,結果這個數據第7s才到,這時候我們是把這個數據放到哪個時間槽上呢?如果是第10s這個數據才到,我們將這個數據是放到當前時間槽還是下一個時間槽上呢?所以,這個heartbeat就是決定我們的數據沒有正常接收,這個值是決定我們的將到來的數據放到哪個時間槽上。比如我們可以定義只要在10s以內就還放在當前時間槽上,如果大於10s,就放到下一個時間槽上。
				min,max:確定可以接收的數據的范圍,超出這個范圍不接收。如果不知道接收數據的准確值是否在這個范圍,就是UNKNOWN
				heartbeat defines the maximum number of seconds that may pass between two updates of this data source before the value of the data source is assumed to be *UNKNOWN* 
				min and max define the expected range values for data supplied by a data source
				
		For COMPUTE data sources,the format is :
			DS:ds-name:COMPUTE:rpn-expression

		初始值:1
		2 3 6 9
		GUAGE:2 3 6 9
		COMPUTE:1 1 3 3
         DERIVE:1 1 3 3 # 可以允許前后兩個數值之差為負數
		ABSOLUTE: 1 2 5 8 # 相對於初始值

		保存網卡流量可以使用COUNTER(只增不減),保存溫度使用DERIVE,GUAGE保存初始值和原有值

# Update命令格式:store new data values into an RRD 在指定的時間范圍內向rrdtool create創建的數據庫中提供數據
rrdtool {update | updatev} filename [--template|-t ds-name[:ds-name]...] [--skip-past-updates|-s] [--daemon|-d address] [--] N:value[:value]... timestamp:value[:value]... at-timestamp@value[:value]...

# Graph命令格式:Create a graph from data stored in one or several RRDs.Apart from generatin graphs,data can also be extracted yo stdout
rrdtool graph|graphv filename [option ...] [data definition ...] [data calculation ...] [variable definition ...] [graph element ...] [print element ...]
	
	filename:生成的圖片的名稱,默認生成的都是.png的圖片
	
	[-s|--start time] [-e|--end time] [-S|--step seconds] # 起始日期、解析度
	[-t|--title string] [-v|--vertical-label string] # 標題,縱向坐標軸名稱
	[-w|width pixels] [-h|height pixels] [-j|--only-graph] [-D|--full-size-mode] # 圖片的寬度、高度、只顯示圖片、全圖
	[-u|--upper-limit value] [-l|--lower-limit value] [-r|--rigid] # 刻度的上下限, -r 不允許縮放
	[-A|--alt-autoscale] # 自動縮放
	[-J|--alt-autoscale-min] # 只自動縮放最小值
	[-M|--alt-autoscale-max] # 只自動縮放最大值
	[-N|--no-gridgit] # 不顯示網格線
	X-Axis # 用於定制橫軸的標識符
		[-x|--x-grid GTM:GST:MTM:MST:LTM:LST:LPR:LFM]  # GTM(單位):GST(時間值)基准網格線跨度,MTM:MST 主網格線,LTM:LST 橫軸的標簽,LPR:LFM 橫軸上多長時間顯示一個標簽
		[-x|--x-grid none]
		e.g --x-grid MINUTE:10:HOUR:1:HOUR:4:0:%X  # %X 指定時間格式
	y-Axis # 用於定制縱軸的標識符
		[-y|--y-grid grid step:label factor] # step每隔多長顯示一個縱軸刻度 label卷標,factor顯示卷標時,每隔多長時間顯示一次
		[-y|--y-grid none]
		[-Y|--alt-y-grid]

	Miscellaneous
		[-c|--color COLORTAG#rrggbb[aa]]
			BACK background
			CANVAS for the background of the actual graph
			SHADEA for the left and top border
			SHADEB for the right and bottom border
			GRID,MGRID for the major grid
			FONT for the color of the font
			AXIS for the axis of the graph
			FRAME for the line around the color spots
			ARROW for the arrow head pointing up and forward
			
		-n|--font FONTTAG:size:[font]
		[-R|--font-render-mode {normal,light,mono}]
		[-a|--imagformat PNG|SVG|EPS|PDF] # 默認是png
		[-W|--watermark string]	# 給圖片打水印		
	# Data and variables
    DEF:vname=rrdfile:ds-name:CF[:step=step][:start=time][:end=time]
    CDEF:vname=RPN expression
    VDEF:vname=RPN expression
        You need at least one DEF and one LINE,AREA,GPRINT,PRINT statement to generate anything useful

    # 畫折線圖還是面積圖?
    # 畫折線圖
    LINE [width]:value[#color][:[legend][:STACK]][:dashes[=on_s[off_s[on_s,off_s]...]][:dash-offse=offset]]

    # 畫面積圖
    AREA:value[#color][:[:legend][:STACK]]
        width can be a floating point number
        If the color is not specified,the drawing is done 'invisibly' 
        Also optional is the legend box and string which will be printed in the legend section if specified
        The value can be generated by DEF,VDEF,and CDEF
        if the optional STACK modifier is used,this line is stacked on top of the previous element which can be a LINE or an AREA

updatav: Operationally equivalent to updata except for output

dump: Dump the contents of an RRD in plain ASCII.In connection with restore you can use this to move an RRD from one computer architecture to another

restore: Restore an RRD in XML format to a binary RRD

fetch: Get data for a certain time period from a RRD. The graph function uses fetch to retrieve its data from an RRD 

tune: Alter setup of an RRD

last: Find the last updte time of an RRD 

info: Get information about an RRD

rrdresize: Change the size of individual RRAs

xport: Export data retrieved from one or several RRDs

flushcached: Flush the values for a specific RRD file from memory

rrdcgi: This is a standalone tool for producing RRD graphs on the fly

# RRA后攜帶的參數

The purpose of an RRD is to store data in the round robin archives(RRA)

RRA:AVERAGE | MIN | MAX | LAST:xff:steps:rows
	1.xff The xfiles factor defines what part of a consolidation interval may be made up from *UNKNOWN* data while the consolidated value is still regarded as known 
		xff后定義的是我所使用的聚合函數的PDP當中有多大的比例為NUKNOWN,要小於這個比例,我們就能猜出這個CDP。
		steps:表示對多少個PDP為一組進行聚合
		rows:表示取多少個CDP。比如我們每5s取一個PDP,每10個PDP取一個RRA(聚合函數),我們至少要保存2天的RRA,如何計算要保存多少行?86400*2/5/10
	2.It is given as the ratio of allowed "UNKNOWN" PDPs to the number of PDPs in the interval. Thus, it ranges from 0 to 1(exclusive)
	3.steps defines how many of these primary data points are used to build a consolidated data point which then goes into the archive
	4.rows defines how mnay generations of data values are kept in an RRA.

PDP:Primary Data Point,主數據節點,存儲在每個時間槽上的數據,這個數據並不是我們關心的數據,我們需要對這些數據做聚合函數計算,比如:每兩兩為一組取平均值,這個這個平均值所在的時間槽數據去畫圖

CDP:Consolidation Data Point,聚合數據節點

resolution:解析度,表示每幾個PDP為一組參與聚合

rrdtool工具安裝及使用

rrdtool不是系統標准帶的,需要下載、編譯、安裝;或者直接使用rpm安裝rpm包

yum install -y rrdtool rrdtool-devel rrdtool-perl


rrdtool create test.rrd --step 5 DS:testds:GAUGE:8:0:U RRA:AVERAGE:0.5:1:17280 RRA:AVERAGE:0.5:10:3456 RRA:AVERAGE:0.5:100:1210 # --step 5 表示每5秒鍾接收一個值,不指定默認是300s

rrd info test.rrd  # 查看文件的格式,如下圖2


rrdtool create test.rrd DS:ds1 DS:ds2 # DS代表數據源:data source,可以有多個
rrdtool update test.rrd N:30:40  # N代表當前時間,30傳給了ds1,40傳給了ds2;也可以指定時間,可以是相對時間、絕對時間、時間戳
rrdtool update test.rrd -t ds2:ds1 40:30  # 如果想自己指定數據源順序  使用-t 選項


rrdtool update test.rrd N:$RANDOM
rrdtool fetch test.rrd AVERAGE # 從一個數據源中取數據


rrdtool graph a.png --step 5 -s 1632421520 -t Test -v vtest DEF:vtest=test.rrd:testds:AVERAGE LINE1:vtest#ff0000:testline  # 如圖3

# 將step 5 和step 50 畫在同一張圖上
rrdtool graph b.png --step 5 -s 1632421520 -t Test -v vtest DEF:vartest=/root/test.rrd:testds:AVERAGE:step=50 DEF:vartest2=/root/test.rrd:testds:AVERAGE:step=50 LINE1:vartest#FF0000:"testline" LINE1:vartest2#00FF00:"testline2"

圖1:

圖2:

圖3:

案例:寫一個腳本連續向test.rrd文件中填充隨機數據

vim genval.sh
	#!/bin/bash
    #
    while true;do
      rrdtool update test.rrd N:$RANDOM
      sleep 5
    done

bash -n genval.sh # 測試腳本
bash -x genval.sh # 單步執行腳本

rrdtool fetch -r 5 test.rrd AVERAGE  # -r 指定解析度,在我們創建test.rrd的時候指定的有每隔5s,10s,50s,當我們所指定的解析度不是我們create時所定義的,那么將選擇解析度更高的展示。比如:-r 7,實際展示的是 -r 5。


rrdtool還具有強大的繪圖功能,可以根據上面fetch的數據進行繪圖。。。。


案例:mysql服務器每5s、50s、500s發生的查詢次數(聚合)的圖:

rrdtool create mysql.rrd --step 3 DS:myselect:COUNTER:5:0:U RRA:AVERAGE:0.5:1:28800 RRA:AVERAGE:0.5:10:2880 RRA:MAX:0.5:10:2880 RRA:LAST:0.5:10:2880

# 可以用shell腳本操作mysql數據庫,使用mysql的-e參數可以執行各種sql的(創建,刪除,增,刪,改、查)等各種操作 。
# -e 相關mysql的sql語句,不用在mysql的提示符下運行mysql,即可以在shell中操作mysql的方法。
# 參考示例:https://blog.csdn.net/feeltouch/article/details/46643065
mysql -e "SHOW GLOBAL STATUS LIKE 'com_select'"
mysql --batch -e "SHOW GLOBAL STATUS LIKE 'com_select'"  # --batch 去掉查詢結果的表格線
mysql --batch -e "SHOW GLOBAL STATUS LIKE 'com_select'" | awk '/Com_select/{print $2}'

編輯一個腳本,每隔3s查詢一次com_select,並將結果寫入到rrd:
vim getselect.sh

    #!/bin/bash
    #
    while true;do
      SELECT=`mysql --batch -e "SHOW GLOBAL STATUS LIKE 'com_select'" | awk '/Com_select/{print $2}'`
      rrdtool update mysql.rrd N:$SELECT
      sleep 3
    done

vim insert.sh
#!/bin/bash
#
for I in {1..200000};do
  mysql -e "insert into testdb.tb1(name) values ('stu$I')"
  mysql -e "select * from testdb.tb1" &> /dev/null
 
done

rrdtool fetch -r 5 mysql.rrd AVERAGE  # -r 解析度
rrdtool fetch -r 30 mysql.rrd AVERAGE
rrdtool fetch -r 30 mysql.rrd AVERAGE
rrdtool fetch -r 5 mysql.rrd MAX

rrdtool last mysql.rrd  # 顯示上一個值在哪個時間點插入的

# 每3s的平均值  如圖1
rrdtool graph mysql.png -s 1632448590 -t "mysql select" -v "selects/3" DEF:select3=mysql.rrd:myselect:AVERAGE:step=3 LINE1:select3#FF0000:"select"  

# 每30s的平均值
rrdtool graph mysql.png -s 1632448590 -t "mysql select" -v "selects/30" DEF:select30=mysql.rrd:myselect:AVERAGE:step=30 LINE1:select30#FF0000:"select"

# 除了希納是30s的平均值,還顯示當前值和最大值  如圖2
rrdtool graph mysql.png -s 1632448590 -t "mysql select" -v "selects/30" DEF:select30=mysql.rrd:myselect:AVERAGE:step=30 DEF:max30=mysql.rrd:myselect:MAX:step=30 DEF:last30=mysql.rrd:myselect:LAST:step=30 LINE1:select30#FF0000:"select" GPRINT:last30:LAST:"CURRENT\:%10.2lf" GPRINT:max30:MAX:"MAXIMUM\:%6.2lf"  

圖1:

圖2:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM