日志记录功能完成,感谢go-logger库

pull/92/head
CHN-STUDENT 2021-01-13 17:00:50 +08:00
parent 1b63e5e657
commit fde504da56
10 changed files with 149 additions and 83 deletions

View File

@ -1 +1,2 @@
*.exe *.exe
*.log

View File

@ -13,13 +13,12 @@ go build .
``` ```
### TODO ### TODO
- 日志记录功能
- 外网连接状态 - 外网连接状态
- 其他算法优化 - 其他算法优化
### 鸣谢 ### 鸣谢
- https://github.com/cppla/ServerStatus - https://github.com/cppla/ServerStatus
- https://github.com/bitcav/nitr-core - https://github.com/phachon/go-logger
- https://github.com/shirou/gopsutil - https://github.com/shirou/gopsutil
- https://github.com/json-iterator/go - https://github.com/json-iterator/go

View File

@ -3,7 +3,10 @@ module awesomeProject
go 1.15 go 1.15
require ( require (
github.com/bitcav/nitr-core v0.0.0-20200823224936-5500912f5599 github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d // indirect
github.com/go-ole/go-ole v1.2.4 // indirect
github.com/json-iterator/go v1.1.10 github.com/json-iterator/go v1.1.10
github.com/phachon/go-logger v0.0.0-20191215032019-86e4227f71ea
github.com/shirou/gopsutil v2.20.7+incompatible github.com/shirou/gopsutil v2.20.7+incompatible
golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e // indirect
) )

View File

@ -1,49 +1,36 @@
github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d h1:G0m3OIz70MZUWq3EgK3CesDbo8upS2Vm9/P3FtgI+Jk= github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d h1:G0m3OIz70MZUWq3EgK3CesDbo8upS2Vm9/P3FtgI+Jk=
github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d/go.mod h1:3eOhrUMpNV+6aFIbp5/iudMxNCF27Vw2OZgy4xEx0Fg= github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d/go.mod h1:3eOhrUMpNV+6aFIbp5/iudMxNCF27Vw2OZgy4xEx0Fg=
github.com/bitcav/nitr-core v0.0.0-20200823224936-5500912f5599 h1:/nmGHaIU/fngJx5CpI4aIUP9TJxuZQkeI3ei8cfbKLo=
github.com/bitcav/nitr-core v0.0.0-20200823224936-5500912f5599/go.mod h1:OdZtuocMmwA7iXbeIwcb740q4PbeVJKJu1vJCyzfYHo=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= github.com/fatih/color v1.7.0 h1:DkWD4oS2D8LGGgTQ6IvwJJXSL5Vp2ffcQg58nFV38Ys=
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
github.com/go-ole/go-ole v1.2.4 h1:nNBDSCOigTSiarFpYE9J/KtEA1IOW4CNeqT9TQDqCxI= github.com/go-ole/go-ole v1.2.4 h1:nNBDSCOigTSiarFpYE9J/KtEA1IOW4CNeqT9TQDqCxI=
github.com/go-ole/go-ole v1.2.4/go.mod h1:XCwSNxSkXRo4vlyPy93sltvi/qJq0jqQhjqQNIwKuxM= github.com/go-ole/go-ole v1.2.4/go.mod h1:XCwSNxSkXRo4vlyPy93sltvi/qJq0jqQhjqQNIwKuxM=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
github.com/jaypipes/ghw v0.6.1 h1:Ewt3mdpiyhWotGyzg1ursV/6SnToGcG4215X6rR2af8=
github.com/jaypipes/ghw v0.6.1/go.mod h1:QOXppNRCLGYR1H+hu09FxZPqjNt09bqUZUnOL3Rcero=
github.com/jaypipes/pcidb v0.5.0 h1:4W5gZ+G7QxydevI8/MmmKdnIPJpURqJ2JNXTzfLxF5c=
github.com/jaypipes/pcidb v0.5.0/go.mod h1:L2RGk04sfRhp5wvHO0gfRAMoLY/F3PKv/nwJeVoho0o=
github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
github.com/json-iterator/go v1.1.10 h1:Kz6Cvnvv2wGdaG/V8yMvfkmNiXq9Ya2KUv4rouJJr68= github.com/json-iterator/go v1.1.10 h1:Kz6Cvnvv2wGdaG/V8yMvfkmNiXq9Ya2KUv4rouJJr68=
github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/mailru/easyjson v0.7.0 h1:aizVhC/NAAcKWb+5QsU1iNOZb4Yws5UO2I+aIprQITM=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/mailru/easyjson v0.7.0/go.mod h1:KAzv3t3aY1NaHWoQz1+4F1ccyAH66Jk7yos7ldAVICs=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/mattn/go-colorable v0.1.4 h1:snbPLB8fVfU9iwbbo30TPtbLRzwWu6aJS6Xh4eaaviA=
github.com/mitchellh/go-homedir v1.0.0 h1:vKb8ShqSby24Yrqr/yDYkuFz8d0WUjys40rvnGC8aR0= github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
github.com/mitchellh/go-ps v1.0.0/go.mod h1:J4lOc8z8yJs6vUwklHw2XEIiT4z4C40KtWVN3nvg8Pg= github.com/mattn/go-isatty v0.0.11 h1:FxPOTFNqGkuDUGi3H/qkUbQO4ZiBa2brKq5r0l8TGeM=
github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLDQ0W1YjYsBW+p8U2u7vzgW2SQVmlNazg= github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLDQ0W1YjYsBW+p8U2u7vzgW2SQVmlNazg=
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/pkg/errors v0.8.0 h1:WdK/asTD0HN+q6hsWO3/vpuAkAr+tw6aNJNDFFf0+qw= github.com/phachon/go-logger v0.0.0-20191215032019-86e4227f71ea h1:IkOONr/u7Wy+j2R4r1eMV8PEuN4kmOhZZNaYxDOF+KQ=
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/phachon/go-logger v0.0.0-20191215032019-86e4227f71ea/go.mod h1:WBIWFH/iYYvuApCvPU+/R6hfX6v0Ogu4apwf0UgzVF0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU=
github.com/shirou/gopsutil v2.20.7+incompatible h1:Ymv4OD12d6zm+2yONe39VSmp2XooJe8za7ngOLW/o/w= github.com/shirou/gopsutil v2.20.7+incompatible h1:Ymv4OD12d6zm+2yONe39VSmp2XooJe8za7ngOLW/o/w=
github.com/shirou/gopsutil v2.20.7+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA= github.com/shirou/gopsutil v2.20.7+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA=
github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ=
github.com/spf13/pflag v1.0.2/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e h1:LwyF2AFISC9nVbS6MgzsaQNSUsRXI49GS+YQ5KX/QH0= golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e h1:LwyF2AFISC9nVbS6MgzsaQNSUsRXI49GS+YQ5KX/QH0=
golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
howett.net/plist v0.0.0-20181124034731-591f970eefbb/go.mod h1:vMygbs4qMhSZSc4lCUl2OEE+rDiIIJAIdR4m7MiMcm0=

View File

@ -11,6 +11,7 @@ package main
import ( import (
"fmt" "fmt"
"github.com/json-iterator/go" "github.com/json-iterator/go"
"github.com/phachon/go-logger"
"io/ioutil" "io/ioutil"
"net" "net"
"os" "os"
@ -195,7 +196,8 @@ func SetupCloseHandler() {
signal.Notify(c, os.Interrupt, syscall.SIGTERM) signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() { go func() {
<-c <-c
fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [main] Ctrl+C pressed in Terminal,Stop client program") logger.Info("[main] Ctrl+C pressed in Terminal,Stop client program")
//fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [main] Ctrl+C pressed in Terminal,Stop client program")
if mainConnect != nil { if mainConnect != nil {
if NETWORKCHECK == true { if NETWORKCHECK == true {
pingValueCU.Stop() pingValueCU.Stop()
@ -217,6 +219,7 @@ var pingValueCU *PingValue
var pingValueCT *PingValue var pingValueCT *PingValue
var pingValueCM *PingValue var pingValueCM *PingValue
func getCurrentDirectory() string { func getCurrentDirectory() string {
dir, err := filepath.Abs(filepath.Dir(os.Args[0])) dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil { if err != nil {
@ -226,20 +229,57 @@ func getCurrentDirectory() string {
return dir return dir
} }
var logger *go_logger.Logger
func main() { func main() {
logger = go_logger.NewLogger()
logger.Detach("console")
// 命令行输出配置
consoleConfig := &go_logger.ConsoleConfig{
Color: true, // 命令行输出字符串是否显示颜色
JsonFormat: true, // 命令行输出字符串是否格式化
Format: "", // 如果输出的不是 json 字符串JsonFormat: false, 自定义输出的格式
}
// 添加 console 为 logger 的一个输出
logger.Attach("console", go_logger.LOGGER_LEVEL_DEBUG, consoleConfig)
// 文件输出配置
fileConfig := &go_logger.FileConfig {
Filename : "./test.log", // 日志输出文件名,不自动存在
// 如果要将单独的日志分离为文件请配置LealFrimeNem参数。
LevelFileName : map[int]string {
logger.LoggerLevel("error"): "./error.log", // Error 级别日志被写入 error .log 文件
logger.LoggerLevel("info"): "./info.log", // Info 级别日志被写入到 info.log 文件中
logger.LoggerLevel("debug"): "./debug.log", // Debug 级别日志被写入到 debug.log 文件中
},
MaxSize : 1024 * 1024, // 文件最大值KB默认值0不限
MaxLine : 100000, // 文件最大行数,默认 0 不限制
DateSlice : "d", // 文件根据日期切分, 支持 "Y" (年), "m" (月), "d" (日), "H" (时), 默认 "no" 不切分
JsonFormat: true, // 写入文件的数据是否 json 格式化
Format: "", // 如果写入文件的数据不 json 格式化,自定义日志格式
}
// 添加 file 为 logger 的一个输出
logger.Attach("file", go_logger.LOGGER_LEVEL_DEBUG, fileConfig)
logger.Info(" [main]Logger init complete")
// Setup our Ctrl+C handler // Setup our Ctrl+C handler
SetupCloseHandler() SetupCloseHandler()
config := NewConfig() config := NewConfig()
path := getCurrentDirectory() + "\\config.json" path := getCurrentDirectory() + "\\config.json"
fmt.Printf(time.Now().Format("2006-01-02 15:04:05")+" [main]Try to load config file from %s\n",path) logger.Infof(" [main]Try to load config file from %s\n",path)
//fmt.Printf(time.Now().Format("2006-01-02 15:04:05")+" [main]Try to load config file from %s\n",path)
data, err := ioutil.ReadFile(path) data, err := ioutil.ReadFile(path)
if err != nil { if err != nil {
fmt.Printf(time.Now().Format("2006-01-02 15:04:05")+" [main]Read config file error:%s\n",err) logger.Alertf(" [main]Read config file error:%s\n",err)
//fmt.Printf(time.Now().Format("2006-01-02 15:04:05")+" [main]Read config file error:%s\n",err)
goto Run goto Run
} }
err = jsoniter.Unmarshal(data, &config) err = jsoniter.Unmarshal(data, &config)
if err != nil { if err != nil {
fmt.Printf(time.Now().Format("2006-01-02 15:04:05")+" [main]Parse config file error:%s\n",err) logger.Errorf(" [main]Parse config file error:%s\n",err)
//fmt.Printf(time.Now().Format("2006-01-02 15:04:05")+" [main]Parse config file error:%s\n",err)
} }
if config.User != "" { if config.User != "" {
USER = config.User USER = config.User
@ -308,58 +348,71 @@ func main() {
} }
run = NewRunInfo() run = NewRunInfo()
run.StartGetRunInfo() run.StartGetRunInfo()
logger.Info("[main] Try to connect server")
for { for {
var err error var err error
mainConnect , err = net.DialTimeout("tcp", SERVER + ":" + strconv.Itoa(PORT),defaulttimeout) mainConnect , err = net.DialTimeout("tcp", SERVER + ":" + strconv.Itoa(PORT),defaulttimeout)
if err != nil { if err != nil {
fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [main]Error listening:", err) logger.Errorf("[main]Error listening:%s\n", err)
//fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [main]Error listening:", err)
} }
defer mainConnect.Close() defer mainConnect.Close()
fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [main]Listening done,get server info now") logger.Info("[main]Listening done,get server info now")
//fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [main]Listening done,get server info now")
buff := make([]byte, 1024) buff := make([]byte, 1024)
mainConnect.Read(buff) mainConnect.Read(buff)
str := bytes2str(buff) str := bytes2str(buff)
if strings.Index(str,"Authentication required") > -1 { if strings.Index(str,"Authentication required") > -1 {
fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [main]Authentication required,send it to server") logger.Info("[main]Authentication required,send it to server")
//fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [main]Authentication required,send it to server")
auth := str2bytes(USER + ":" + PASSWORD + "\n") auth := str2bytes(USER + ":" + PASSWORD + "\n")
_ , err = mainConnect.Write(auth) _ , err = mainConnect.Write(auth)
if err != nil { if err != nil {
fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [main]Error sending auth info:", err) logger.Errorf("[main]Error sending auth info:", err)
//fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [main]Error sending auth info:", err)
return return
} }
buff = make([]byte, 1024) buff = make([]byte, 1024)
_ , err = mainConnect.Read(buff) _ , err = mainConnect.Read(buff)
if err != nil { if err != nil {
fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [main]Error getting server data:", err) logger.Errorf("[main]Error getting server data:", err)
//fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [main]Error getting server data:", err)
return return
} }
str = bytes2str(buff) str = bytes2str(buff)
if strings.Index(str,"Authentication required") < 0 { if strings.Index(str,"Authentication required") < 0 {
if strings.Index(str,"Wrong username and/or password.") > -1 { if strings.Index(str,"Wrong username and/or password.") > -1 {
fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [main]Wrong username and/or password.") logger.Errorf(" [main]Wrong username and/or password.")
//fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [main]Wrong username and/or password.")
return return
}else if strings.Index(str,"Authentication successful. Access granted.") > -1 { }else if strings.Index(str,"Authentication successful. Access granted.") > -1 {
fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [main]Authentication successful. Access granted.") logger.Info("[main]Authentication successful. Access granted.")
//fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [main]Authentication successful. Access granted.")
} else { } else {
fmt.Println(str) logger.Error(str)
//fmt.Println(str)
return return
} }
} }
} else if strings.Index(str,"You have been banned for 1 minute (Wrong username and/or password.)") > -1{ } else if strings.Index(str,"You have been banned for 1 minute (Wrong username and/or password.)") > -1{
fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [main]You have been banned for 1 minute (Wrong username and/or password.)") logger.Alert("[main]You have been banned for 1 minute (Wrong username and/or password.)")
//fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [main]You have been banned for 1 minute (Wrong username and/or password.)")
return return
} else { } else {
logger.Error(str)
fmt.Println(str) fmt.Println(str)
} }
if strings.Index(str,"You are connecting via") < 0 { if strings.Index(str,"You are connecting via") < 0 {
buff = make([]byte, 1024) buff = make([]byte, 1024)
_ , err = mainConnect.Read(buff) _ , err = mainConnect.Read(buff)
if err != nil { if err != nil {
fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [main]Error getting server data:", err) logger.Errorf("[main]Error getting server data:", err)
//fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [main]Error getting server data:", err)
return return
} }
str = bytes2str(buff) str = bytes2str(buff)
fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [main]"+str) //logger.Info("[main] " + str)
//fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [main]"+str)
} }
//var checkIP int = 0 //var checkIP int = 0
//if strings.Index(str,"IPv4") > -1 { //if strings.Index(str,"IPv4") > -1 {
@ -401,12 +454,15 @@ func main() {
data, err := clientInfo.MarshalToString() data, err := clientInfo.MarshalToString()
//fmt.Println(data) //fmt.Println(data)
if err != nil { if err != nil {
fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [main]Error transforming client info: ", err) logger.Errorf("[main]Error transforming client info: ", err)
//fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [main]Error transforming client info: ", err)
break break
} }
logger.Info("\nInfo:\n"+data+"\n")
info := "update " + data + "\n" info := "update " + data + "\n"
_ , err = mainConnect.Write(str2bytes(info)) _ , err = mainConnect.Write(str2bytes(info))
if err != nil { if err != nil {
logger.Errorf("[main]Error sending client info:", err)
fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [main]Error sending client info:", err) fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [main]Error sending client info:", err)
break break
} }

View File

@ -1,7 +1,6 @@
package main package main
import ( import (
"fmt"
nnet "github.com/shirou/gopsutil/net" nnet "github.com/shirou/gopsutil/net"
"strings" "strings"
"sync" "sync"
@ -46,7 +45,8 @@ func (netSpeed *NetSpeed) Run() {
var bytesRecv uint64 = 0 var bytesRecv uint64 = 0
netInfo, err := nnet.IOCounters(true) netInfo, err := nnet.IOCounters(true)
if err != nil { if err != nil {
fmt.Println(time.Now().Format("2006-01-02 15:04:05")," Get network speed error:",err) logger.Errorf("Get network speed error:",err)
//fmt.Println(time.Now().Format("2006-01-02 15:04:05")," Get network speed error:",err)
} }
for _, v := range netInfo { for _, v := range netInfo {
if strings.Index(v.Name,"lo") > -1 || if strings.Index(v.Name,"lo") > -1 ||

View File

@ -1,7 +1,6 @@
package main package main
import ( import (
"fmt"
"net" "net"
"sync" "sync"
"time" "time"
@ -43,7 +42,8 @@ func (pingValue *PingValue) RunCU() {
t := time.Now() t := time.Now()
conn , err := net.DialTimeout("tcp",CU_ADDR,defaulttimeout) conn , err := net.DialTimeout("tcp",CU_ADDR,defaulttimeout)
if err != nil { if err != nil {
fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [ping]Error try to connect China unicom :", err) logger.Alertf("[ping]Error try to connect China Unicom :", err)
//fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [ping]Error try to connect China unicom :", err)
lostConnect = true lostConnect = true
lostPacket += 1 lostPacket += 1
} }
@ -102,7 +102,8 @@ func (pingValue *PingValue) RunCT() {
t := time.Now() t := time.Now()
conn , err := net.DialTimeout("tcp",CT_ADDR,defaulttimeout) conn , err := net.DialTimeout("tcp",CT_ADDR,defaulttimeout)
if err != nil { if err != nil {
fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [ping]Error try to connect China Telecom :", err) logger.Alertf("[ping]Error try to connect China Telecom :", err)
//fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [ping]Error try to connect China Telecom :", err)
lostConnect = true lostConnect = true
lostPacket += 1 lostPacket += 1
} }
@ -157,7 +158,8 @@ func (pingValue *PingValue) RunCM() {
t := time.Now() t := time.Now()
conn , err := net.DialTimeout("tcp",CM_ADDR,defaulttimeout) conn , err := net.DialTimeout("tcp",CM_ADDR,defaulttimeout)
if err != nil { if err != nil {
fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [ping]Error try to connect China mobile :", err) logger.Alertf("[ping]Error try to connect China Mobile :", err)
//fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [ping]Error try to connect China mobile :", err)
lostConnect = true lostConnect = true
lostPacket += 1 lostPacket += 1
} }

View File

@ -1,16 +1,15 @@
package main package main
import ( import (
"fmt"
"strings"
"sync"
"time"
"github.com/shirou/gopsutil/host"
"github.com/shirou/gopsutil/cpu" "github.com/shirou/gopsutil/cpu"
"github.com/shirou/gopsutil/disk" "github.com/shirou/gopsutil/disk"
"github.com/shirou/gopsutil/host"
"github.com/shirou/gopsutil/load" "github.com/shirou/gopsutil/load"
"github.com/shirou/gopsutil/mem" "github.com/shirou/gopsutil/mem"
nnet "github.com/shirou/gopsutil/net" nnet "github.com/shirou/gopsutil/net"
"strings"
"sync"
"time"
) )
type Run struct { type Run struct {
@ -85,7 +84,8 @@ func (run *Run) StartGetRunInfo() {
run.mtx.Lock() run.mtx.Lock()
memInfo, err := mem.VirtualMemory() memInfo, err := mem.VirtualMemory()
if err != nil { if err != nil {
fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [getInfo]Get memory usage error:",err) logger.Errorf("[getInfo]Get memory usage error:",err)
//fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [getInfo]Get memory usage error:",err)
run.memoryTotal = 0 run.memoryTotal = 0
run.memoryUsed = 0 run.memoryUsed = 0
} else { } else {
@ -95,18 +95,21 @@ func (run *Run) StartGetRunInfo() {
totalPercent, err := cpu.Percent(time.Second, false) totalPercent, err := cpu.Percent(time.Second, false)
if err != nil { if err != nil {
fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [GetInfo]Get cpu usage error:",err) logger.Errorf("[getInfo]Get cpu usage error:",err)
//fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [GetInfo]Get cpu usage error:",err)
run.CPU = 0.0 run.CPU = 0.0
} else { } else {
if totalPercent != nil { if totalPercent != nil {
run.CPU = totalPercent[0] run.CPU = totalPercent[0]
} else { } else {
fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [getInfo]Get cpu usage error:",err) logger.Errorf("[getInfo]Get cpu usage error:",err)
//fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [getInfo]Get cpu usage error:",err)
} }
} }
hInfo, err := host.Info() hInfo, err := host.Info()
if err != nil { if err != nil {
fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [getInfo]get uptime error",err) logger.Errorf("[getInfo]get uptime error",err)
//fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [getInfo]get uptime error",err)
run.uptime = 0 run.uptime = 0
} else { } else {
run.uptime = hInfo.Uptime run.uptime = hInfo.Uptime
@ -114,7 +117,8 @@ func (run *Run) StartGetRunInfo() {
//swap 没有造好的轮子,自己加的 //swap 没有造好的轮子,自己加的
swapMemory, err := mem.SwapMemory() swapMemory, err := mem.SwapMemory()
if err != nil { if err != nil {
fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [getInfo]Get swap memory error:",err) logger.Errorf("[getInfo]Get swap memory error:",err)
//fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [getInfo]Get swap memory error:",err)
run.swapTotal = 0 run.swapTotal = 0
run.swapUsed = 0 run.swapUsed = 0
} else { } else {
@ -134,7 +138,8 @@ func (run *Run) StartGetRunInfo() {
func trafficCount() { func trafficCount() {
netInfo, err := nnet.IOCounters(true) netInfo, err := nnet.IOCounters(true)
if err != nil { if err != nil {
fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [trafficCount]Getting traffic count error:",err) logger.Errorf("[trafficCount]Getting traffic count error:",err)
//fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [trafficCount]Getting traffic count error:",err)
} }
var bytesSent uint64 = 0 var bytesSent uint64 = 0
var bytesRecv uint64 = 0 var bytesRecv uint64 = 0
@ -195,7 +200,8 @@ func getLoad() {
// linux or freebsd only // linux or freebsd only
hInfo, err := host.Info() hInfo, err := host.Info()
if err != nil { if err != nil {
fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [getLoad]get load info error",err) logger.Errorf("[getLoad]Get load info error",err)
//fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [getLoad]get load info error",err)
run.load1 = 0.0 run.load1 = 0.0
run.load5 = 0.0 run.load5 = 0.0
run.load15 = 0.0 run.load15 = 0.0
@ -203,7 +209,8 @@ func getLoad() {
if hInfo.OS == "linux" || hInfo.OS == "freebsd" { if hInfo.OS == "linux" || hInfo.OS == "freebsd" {
l, err := load.Avg() l, err := load.Avg()
if err != nil { if err != nil {
fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [getLoad]Get CPU loads failed:",err) logger.Errorf("[getLoad]Get CPU loads failed:",err)
//fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [getLoad]Get CPU loads failed:",err)
run.load1 = 0.0 run.load1 = 0.0
run.load5 = 0.0 run.load5 = 0.0
run.load15 = 0.0 run.load15 = 0.0

View File

@ -1,8 +1,8 @@
// +build linux // +build linux
package main package main
import ( import (
"fmt"
"os/exec" "os/exec"
"strconv" "strconv"
"strings" "strings"
@ -11,52 +11,60 @@ func tupd() {
byte1 ,err := exec.Command("bash", "-c","ss -t|wc -l").Output() byte1 ,err := exec.Command("bash", "-c","ss -t|wc -l").Output()
if err != nil { if err != nil {
clientInfo.TCP = 0 clientInfo.TCP = 0
fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [tupd]Get TCP count error:",err) logger.Errorf("[tupd]Get TCP count error:",err)
//fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [tupd]Get TCP count error:",err)
} else { } else {
result := bytes2str(byte1) result := bytes2str(byte1)
result = strings.Replace(result, "\n", "", -1) result = strings.Replace(result, "\n", "", -1)
intNum, err := strconv.Atoi(result) intNum, err := strconv.Atoi(result)
if err != nil { if err != nil {
fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [tupd]Get TCP count error::",err) logger.Errorf("[tupd]Get TCP count error:",err)
//fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [tupd]Get TCP count error::",err)
} }
clientInfo.TCP = uint64(intNum) clientInfo.TCP = uint64(intNum)
} }
byte2 ,err := exec.Command("bash", "-c","ss -u|wc -l").Output() byte2 ,err := exec.Command("bash", "-c","ss -u|wc -l").Output()
if err != nil { if err != nil {
clientInfo.UDP = 0 clientInfo.UDP = 0
fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [tupd]Get UDP count error:",err) logger.Errorf("[tupd]Get UDP count error:",err)
//fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [tupd]Get UDP count error:",err)
} else { } else {
result := bytes2str(byte2) result := bytes2str(byte2)
result = strings.Replace(result, "\n", "", -1) result = strings.Replace(result, "\n", "", -1)
intNum, err := strconv.Atoi(result) intNum, err := strconv.Atoi(result)
if err != nil { if err != nil {
fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [tupd]Get UDP count error:",err) logger.Errorf("[tupd]Get UDP count error:",err)
//fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [tupd]Get UDP count error:",err)
} }
clientInfo.UDP = uint64(intNum) clientInfo.UDP = uint64(intNum)
} }
byte3 ,err := exec.Command("bash", "-c","ps -ef|wc -l").Output() byte3 ,err := exec.Command("bash", "-c","ps -ef|wc -l").Output()
if err != nil { if err != nil {
clientInfo.Process = 0 clientInfo.Process = 0
fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [tupd]Get process count error:",err) logger.Errorf("[tupd]Get process count error:",err)
//fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [tupd]Get process count error:",err)
} else { } else {
result := bytes2str(byte3) result := bytes2str(byte3)
result = strings.Replace(result, "\n", "", -1) result = strings.Replace(result, "\n", "", -1)
intNum, err := strconv.Atoi(result) intNum, err := strconv.Atoi(result)
if err != nil { if err != nil {
fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [tupd]Get process count error:",err) logger.Errorf("[tupd]Get process count error:",err)
//fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [tupd]Get process count error:",err)
} }
clientInfo.Process = uint64(intNum) clientInfo.Process = uint64(intNum)
} }
byte4 ,err := exec.Command("bash", "-c","ps -eLf|wc -l").Output() byte4 ,err := exec.Command("bash", "-c","ps -eLf|wc -l").Output()
if err != nil { if err != nil {
clientInfo.Process = 0 clientInfo.Process = 0
fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [tupd]Get threads count error:",err) logger.Errorf("[tupd]Get threads count error:",err)
//fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [tupd]Get threads count error:",err)
} else { } else {
result := bytes2str(byte4) result := bytes2str(byte4)
result = strings.Replace(result, "\n", "", -1) result = strings.Replace(result, "\n", "", -1)
intNum, err := strconv.Atoi(result) intNum, err := strconv.Atoi(result)
if err != nil { if err != nil {
fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [tupd]Get threads count error:",err) logger.Errorf("[tupd]Get threads count error:",err)
//fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [tupd]Get threads count error:",err)
} }
clientInfo.Thread = uint64(intNum) clientInfo.Thread = uint64(intNum)
} }

View File

@ -1,21 +1,20 @@
package main package main
import ( import (
"fmt"
"github.com/shirou/gopsutil/process" "github.com/shirou/gopsutil/process"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
"strconv" "strconv"
"strings" "strings"
"syscall" "syscall"
"time"
) )
func tupd() { func tupd() {
cmd ,err := Command("cmd","/c netstat -an|find \"TCP\" /c") cmd ,err := Command("cmd","/c netstat -an|find \"TCP\" /c")
if err != nil { if err != nil {
clientInfo.TCP = 0 clientInfo.TCP = 0
fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [tupd]Get TCP count error:",err) logger.Errorf("[tupd]Get TCP count error:",err)
//fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [tupd]Get TCP count error:",err)
} else { } else {
byte1, err := cmd.Output() byte1, err := cmd.Output()
result := bytes2str(byte1) result := bytes2str(byte1)
@ -23,14 +22,16 @@ func tupd() {
result = strings.Replace(result, "\n", "", -1) result = strings.Replace(result, "\n", "", -1)
intNum, err := strconv.Atoi(result) intNum, err := strconv.Atoi(result)
if err != nil { if err != nil {
fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [tupd]Get TCP count error:",err) logger.Errorf("[tupd]Get TCP count error:",err)
//fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [tupd]Get TCP count error:",err)
} }
clientInfo.TCP = uint64(intNum) clientInfo.TCP = uint64(intNum)
} }
cmd2 ,err := Command("cmd", "/c netstat -an|find \"UDP\" /c") cmd2 ,err := Command("cmd", "/c netstat -an|find \"UDP\" /c")
if err != nil { if err != nil {
clientInfo.UDP = 0 clientInfo.UDP = 0
fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [tupd]Get UDP count error:",err) logger.Errorf("[tupd]Get UDP count error:",err)
//fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [tupd]Get UDP count error:",err)
} else { } else {
byte2, err := cmd2.Output() byte2, err := cmd2.Output()
result := bytes2str(byte2) result := bytes2str(byte2)
@ -38,13 +39,15 @@ func tupd() {
result = strings.Replace(result, "\n", "", -1) result = strings.Replace(result, "\n", "", -1)
intNum, err := strconv.Atoi(result) intNum, err := strconv.Atoi(result)
if err != nil { if err != nil {
fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [tupd]Get UDP count error:",err) logger.Errorf("[tupd]Get UDP count error:",err)
//fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [tupd]Get UDP count error:",err)
} }
clientInfo.UDP = uint64(intNum) clientInfo.UDP = uint64(intNum)
} }
pids, err := process.Processes() pids, err := process.Processes()
if err != nil { if err != nil {
fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [tupd]Get process count error:",err) logger.Errorf("[tupd]Get process count error:",err)
//fmt.Println(time.Now().Format("2006-01-02 15:04:05")," [tupd]Get process count error:",err)
} else { } else {
clientInfo.Process = uint64(len(pids)) clientInfo.Process = uint64(len(pids))
} }