9月 18

snmp 交换机 带宽计算 python

交换机设置SNMP协议,例为V2C版本,获取接口速度。

<code>def getData():
     shost = "192.168.0.2"
     sDevport = "20"
     sin1 = os.popen('snmpwalk -v 2c -c pass ' + \
                      shost + ' IF-MIB::ifHCInOctets.'+ \
                     sDevport).read()[:-1].split()[-1]
     sout1 = os.popen('snmpwalk -v 2c -c pass ' + \
                       shost + ' IF-MIB::ifHCOutOctets.'+ \
                       sDevport).read()[:-1].split()[-1]
     time.sleep(5)
     sin2 = os.popen('snmpwalk -v 2c -c pass ' + \
                      shost + ' IF-MIB::ifHCInOctets.'+ \
                      sDevport).read()[:-1].split()[-1]
     sout2 = os.popen('snmpwalk -v 2c -c pass ' + \
                       shost + ' IF-MIB::ifHCOutOctets.'+ \
                       sDevport).read()[:-1].split()[-1]
     inT = round((float(sin2) - float(sin1))*8/1024/1024/5, 2)
     outT = round((float(sout2) - float(sout1))*8/1024/1024/5, 2)
     return inT, outT</code>

踩坑列表

1)sDevport 端口不是设备的物理端口。如交换机25口,用命令snmpwalk -v 2c -c pass 192.168.1.2 |grep 25,查找 IF-MIB::ifDescr.XX。XX为扩展的口。

2)不要是用IF-MIB::ifInOctets.XX,用IF-MIB::ifHCInOctets.XX。前者为32位,后者为64位记录。前者容易满计算麻烦。

3)交换机返回的为累加统计,所以需要中间等待后,再次获取,计算两次的差。

4)返回的值为byte,需要先乘8,计算为bit然后再除1024,计算进位量。

9月 13

golang 自动编译脚本、带版本、格式整理和压缩

开发环境:
centos x86_64 7.3
golang 1.12.3

使用yum安装 upx用于压缩
golang代码main.go部分:

import (
"flag"
"fmt"
"os"
)
var (
VERSION = "unknown"
showVer bool
)
func main() {
flag.BoolVar(&showVer, "V", false, "show version and exit")
flag.Parse()
if showVer {
fmt.Println("version:", _VERSION_)
os.Exit(0)
}
/*主代码*/
}
编译文件Makefile
.PHONY: build clean tool  help
BUILD_VERSION := v0.0.1
programName = "testVersion"
all: build
build:
@go build -v -ldflags "-s -w \
-X main.VERSION=${BUILD_VERSION}" .
bb:
@go build -v -ldflags "-s -w" .
upx -9 $(programName)
tool:
go vet ./…; true
gofmt -w .
clean:
go clean -i .
help:
@echo "make: compile packages and dependencies"
@echo "make tool: run specified go tool"
@echo "make clean: remove object files and cached files"
自动执行autoMake.sh
!/bin/env bash
nPath=pwd
softName=basename $nPath
rm -rf $softName
find . -name ".go" -not -path "./vendor/" -not -path ".git/*" | xargs gofmt -s -d -w
make
upx -9 $softName

执行autoMake.sh,完成编译。

执行 ./testVersion -V 显示版本,不输入直接执行。