go 语言使用ssh包连接操作Linux服务器,使用ping包查看服务器网络是否正常,使用cron包定时查询该服务器CPU使用情况

1、在https://www.golangtc.com/download/package输入
golang.org/x/crypto/ssh下载ssh第三方包ssh,同样方法下载cron包和ping包
2、如何使用ssh操作Linux服务器

package controllers
import (
    . "domain/model"
    "bytes"
    "fmt"
    "infrastructure/log"
    "infrastructure/remote"
    "io/ioutil"
    "net"
    "strconv"
    "strings"
    "time"
    "golang.org/x/crypto/ssh"
    "infrastructure/github.com/cron"
    "infrastructure/github.com/paulstuart/ping"
    "infrastructure/github.com/ripple"
)
type AnalyseController struct {
}
var (
    client  *ssh.Client
    session *ssh.Session
    err     error
    ctx     *ripple.Context
)
var (
    IpAddress = []string{"127.0.0.1"}
    IpAddressmap = map[string]string{"127.0.0.1": "正常"}
    IpAddressPort = []string{"127.0.0.1:8080"}
    IpPassword = []string{"***"}
)
func NewMonitorController() *AnalyseController {
    output := new(AnalyseController)
    return output
}

//是否正常运行
func (this *AnalyseController) GetMonitorStatusNormal() {
    cronInstance := cron.New()
    this.cronTask(cronInstance)
    cronInstance.Start()
}
func (this *AnalyseController) cronTask(cronInstance *cron.Cron) {
    //  spec := "*/2 * * * * ?"//每 秒查看微服务是否正常
    spec := "0 */2 * * * ?" //每 分钟查看微服务是否正常
    cronInstance.AddFunc(spec, this.getMicroserviceStatus)
    cronInstance.AddFunc(spec, this.getMonitorResult)
}
func (this *AnalyseController) getMonitorResult() {
    startTime := time.Now()
    defer func() {
        log.Info("monitorresult store start time:", startTime)
        log.Info("monitorresult store end time:", time.Now())
    }()
    log.Error("monitorresult")
    Serviceresultslice := make([]interface{}, 0, 15)
    for i := 0; i < len(IpAddressPort); i++ {
        ServiceCheck := make(map[string]interface{})
        microerviceStatus := make(map[string]string)
        ServiceCheck["IP"] = IpAddress[i]
        alive := ping.Ping(IpAddress[i], 1)//ping查看服务器网络是否正常
        if alive == true {
            ServiceCheck["状态"] = "正常"
            client, err = ssh.Dial("tcp", IpAddressPort[i], &ssh.ClientConfig{
                User: "root",
                Auth: []ssh.AuthMethod{
                    ssh.Password(IpPassword[i]),
                },
                //需要验证服务端,不做验证返回nil就可以,点击HostKeyCallback看源码就知道了,若不加这句,会报错,说没有经过验证
                HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
                    return nil
                },
            })
            if client == nil {
                continue
            }
            if err != nil {
                log.Error("client", err)
                continue
            }
            checkCpu(client, ServiceCheck)
            client.Close()
        } else {
            ServiceCheck["状态"] = "异常"
            ServiceCheck["CPU使用率"] = "NA"
        }
        Serviceresultslice = append(Serviceresultslice, ServiceCheck)
        //          session.Close()
        client.Close()//勿忘关闭
    }
    log.Error("Serviceresultslice", Serviceresultslice)
    Serviceresult = Serviceresultslice
}
func checkCpu(client *ssh.Client, ServiceCheck map[string]interface{}) {
    if session, err = client.NewSession(); err != nil {
        log.Error(err)
    }
    var result bytes.Buffer
    defer session.Close()
    session.Stdout = &result
    session.Stderr = &result
    //  time.Sleep(time.Second)
    session.Run("top -b -n 2 | grep Cpu") //top -b -n 1 | grep Cpu  -n 1第一次显示的为系统开机到当前时刻的平均值,-n 2为实时更新的
    resultstring := result.String()
    resultcpuslice := strings.Split(resultstring, " ") //
    ServiceCheck["CPU使用率"] = ""
    j := 0
    for i := 0; i < len(resultcpuslice); i++ {
        if resultcpuslice[i] == "us," {
            j++
        }
        if j == 2 {
            ServiceCheck["CPU使用率"] = resultcpuslice[i-1] + "%/" + resultcpuslice[i+2] + "%"
            break
        }
    }
    session.Close()//勿忘关闭
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值