shirou_gopsutil/host_freebsd.go

82 lines
1.3 KiB
Go
Raw Normal View History

2014-04-22 11:04:16 +08:00
// +build freebsd
package gopsutil
import (
2014-04-22 16:45:39 +08:00
"bytes"
"encoding/binary"
"io/ioutil"
2014-04-22 11:04:16 +08:00
"os"
"strconv"
2014-04-22 11:43:31 +08:00
"strings"
2014-04-22 16:45:39 +08:00
"unsafe"
2014-04-22 11:04:16 +08:00
)
func HostInfo() (HostInfoStat, error) {
ret := HostInfoStat{}
hostname, err := os.Hostname()
ret.Hostname = hostname
if err != nil {
return ret, err
}
return ret, nil
}
2014-04-30 14:32:05 +08:00
func BootTime() (int64, error) {
2014-04-30 15:16:07 +08:00
values, err := doSysctrl("kern.boottime")
2014-04-22 11:04:16 +08:00
if err != nil {
return 0, err
}
// ex: { sec = 1392261637, usec = 627534 } Thu Feb 13 12:20:37 2014
v := strings.Replace(values[2], ",", "", 1)
boottime, err := strconv.ParseInt(v, 10, 64)
if err != nil {
return 0, err
}
return boottime, nil
}
2014-04-22 16:45:39 +08:00
func Users() ([]UserStat, error) {
utmpfile := "/var/run/utmp"
2014-04-30 15:16:07 +08:00
var ret []UserStat
2014-04-22 16:45:39 +08:00
file, err := os.Open(utmpfile)
if err != nil {
return ret, err
}
buf, err := ioutil.ReadAll(file)
if err != nil {
return ret, err
}
u := utmp{}
entrySize := int(unsafe.Sizeof(u))
count := len(buf) / entrySize
for i := 0; i < count; i++ {
b := buf[i*entrySize : i*entrySize+entrySize]
var u utmp
br := bytes.NewReader(b)
err := binary.Read(br, binary.LittleEndian, &u)
if err != nil {
continue
}
user := UserStat{
2014-04-30 15:19:39 +08:00
User: byteToString(u.UtName[:]),
Terminal: byteToString(u.UtLine[:]),
Host: byteToString(u.UtHost[:]),
Started: int(u.UtTime),
2014-04-22 16:45:39 +08:00
}
ret = append(ret, user)
}
return ret, nil
}