基于go语言写了一个简单的磁盘监控脚本,兼容linux和windows,
具体实现代码如下:
- package main
-
- import (
- "database/sql"
- "fmt"
- _ "github.com/go-sql-driver/mysql"
- "github.com/shirou/gopsutil/v3/disk"
- "log"
- Lnet "net"
- "os"
- "strconv"
- "strings"
- "time"
- )
- var MysqlDB *sql.DB
- var MysqlErr error
- var dbDsn string
- var dbSourceInfo string
- func Initdb(){
-
- os.Setenv("NLS_LANG", "SIMPLIFIED CHINESE_CHINA.AL32UTF8")
- user:="xxxx"
- passwd:="xxxx"
- hostIp:="xxxx"
- port:="xxxx"
- dbname:="xxxx"
- charset:="utf8mb4"
- dbDsn:=fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&timeout=5s&readTimeout=5s&writeTimeout=5s", user, passwd, hostIp, port, dbname, charset)
- dbSourceInfo =fmt.Sprintf("%s:%s/%s",hostIp, port, dbname)
- //log.Println(dbDsn)
- //log.Println(dbSourceInfo)
- //打开连接
- MysqlDB,MysqlErr= sql.Open("mysql",dbDsn)
- //log.Println(MysqlErr)
-
-
- //checkErr(dbDsn,1,1,MysqlErr)
- //log.Println(MysqlDB)
- //最大连接
- MysqlDB.SetMaxOpenConns(2)
-
- //闲置空闲连接
- MysqlDB.SetMaxIdleConns(2)
- //最大连接周期
- MysqlDB.SetConnMaxLifetime(10)
-
- if MysqlErr = MysqlDB.Ping(); nil != MysqlErr {
- os.Exit(1)
- //checkErr(dbDsn,1,1,MysqlErr)
- }
-
- }
- func getDiskInfo() {
-
- parts, _ := disk.Partitions(true)
-
- diskTime := time.Now().Format("2006-01-02 15:04:05")
- localIp:=GetOutboundIP()
- disks := ""
- for _, part := range parts {
- fsType := part.Fstype
- if fsType == "xfs" || fsType == "ext2" || fsType == "ext3" || fsType == "ext4" || fsType == "nfs" || fsType == "NTFS" || fsType == "nfs4" || fsType == "NTFS4" ||fsType == "cifs" {
- diskInfo, _ := disk.Usage(part.Mountpoint)
- disks += part.Mountpoint + ","
- diskPct, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", diskInfo.UsedPercent), 64)
- //checkErr(ins.fIp,4,1,errPct)
- DiskAlarm := Query(MysqlDB, dbDsn, 1, 1, " select f_alarm_disk as value from t_options order by f_update_time desc limit 1")[0]["value"]
- fDiskAlarm, _ := strconv.ParseFloat(DiskAlarm, 64)
- if fDiskAlarm == 0 {
- fDiskAlarm = 90
- }
- log.Printf(part.Mountpoint)
- if strings.Contains(part.Mountpoint, "archivelog") {
- if diskPct>=50{
- msg := fmt.Sprintf("%v used space is higher last_value:%v%%", part.Mountpoint, diskPct)
- msgError := fmt.Sprintf("Problem!! %s %s %s", localIp, msg, diskTime)
- //sendSms(toAddress,msgError,"LTAIiGjULxYERylh","YIIGlydOAUyZVEIjvvAA33WFCCko5G",
- // "智创博为","SMS_219743608","name")
- inSql := fmt.Sprintf("insert into t_alarm_send_info(f_send_type,f_send_level,f_send_info) values(%v,%v,'%v')", 3, 'C', msgError)
- //log.Println(inSql)
- Exec(MysqlDB, dbSourceInfo, 1, 1, inSql)
- }
- } else {
- if diskPct > fDiskAlarm {
- msg := fmt.Sprintf("%v used space is higher last_value:%v%%", part.Mountpoint, diskPct)
- msgError := fmt.Sprintf("Problem!! %s %s %s", localIp, msg, diskTime)
- //sendSms(toAddress,msgError,"LTAIiGjULxYERylh","YIIGlydOAUyZVEIjvvAA33WFCCko5G",
- // "智创博为","SMS_219743608","name")
- inSql := fmt.Sprintf("insert into t_alarm_send_info(f_send_type,f_send_level,f_send_info) values(%v,%v,'%v')", 3, 'C', msgError)
- //log.Println(inSql)
- Exec(MysqlDB, dbSourceInfo, 1, 1, inSql)
- }
- }
- }
- }
- }
-
- //func sendSms(to string,msg string,AccessKeyId string,AccessKeySecret string,SignName string,TemplateCode string,TemplateParam string) {
- // client, _ := dysmsapi.NewClientWithAccessKey("cn-hangzhou", AccessKeyId, AccessKeySecret)
- // request := dysmsapi.CreateSendSmsRequest()
- // request.Scheme = "https"
- // msg = strings.Replace(msg, "\"", "", -1)
- // request.PhoneNumbers = to
- // request.SignName = SignName
- // request.TemplateCode = TemplateCode
- // request.TemplateParam = "{\"" + TemplateParam + "\":\"" + msg + "\"}"
- //
- // response, _ := client.SendSms(request)
- // log.Println(errors.New(response.Message).Error())
- //
- //}
- func Exec(db *sql.DB,dbInfo string,types int ,level int,query string){
- _,err:=db.Exec(query)
- log.Println(err)
- }
- func Query(db *sql.DB,dbinfo string,types int ,level int,query string)(result map[int]map[string]string) {
- rows,_ := db.Query(query)
- defer rows.Close()
- cols,_ :=rows.Columns() //返回所有列
- vals :=make([][]byte,len(cols)) //这里表示一行所有列的值,用[]byte表示
- scans :=make([]interface{},len(cols)) //这里表示一行填充数据
- for k,_:=range vals{
- scans[k] = &vals[k]
- }
- i :=0
- result = make(map[int]map[string]string)
- for rows.Next(){
- rows.Scan(scans...) //填充数据
- row :=make(map[string]string) //每行数据
- for k,v := range vals { //把vals中的数据复制到row中
- key :=cols[k]
- //fmt.Println(string(v)) //这里把[]byte数据转成string
- row[key] = string(v)
- }
- result[i] = row
- i++
- }
- rows.Close()
- return result
- }
- func GetOutboundIP() string {
- conn, err := Lnet.Dial("udp", "8.8.8.8:80")
- if err != nil {
- //dbLog("自动获取ip失败",1,1,err.Error())
- panic(err)
- }
- defer conn.Close()
- localAddr := conn.LocalAddr().(*Lnet.UDPAddr)
- return localAddr.IP.String()
- }
- func main(){
- Initdb()
- getDiskInfo()
- }