常用类型及数据操作方法
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

478 lines
9.9 KiB

3 years ago
  1. /*
  2. * System info
  3. */
  4. package helper
  5. import (
  6. "bytes"
  7. "errors"
  8. "fmt"
  9. "io/ioutil"
  10. "log"
  11. "os/exec"
  12. "regexp"
  13. "strconv"
  14. "strings"
  15. )
  16. func CpuUsage() string {
  17. cmd := exec.Command("ps", "aux")
  18. var out bytes.Buffer
  19. cmd.Stdout = &out
  20. err := cmd.Run()
  21. if err != nil {
  22. return ""
  23. }
  24. var all float64
  25. for {
  26. line, err := out.ReadString('\n')
  27. if err != nil {
  28. break
  29. }
  30. tokens := strings.Split(line, " ")
  31. ft := make([]string, 0)
  32. for _, t := range tokens {
  33. if t != "" && t != "\t" {
  34. ft = append(ft, t)
  35. }
  36. }
  37. if ft[2] == "%CPU" {
  38. continue
  39. }
  40. cpu, err := strconv.ParseFloat(ft[2], 64)
  41. if err != nil {
  42. continue
  43. }
  44. all += cpu
  45. }
  46. return fmt.Sprintf("%.2f", all)
  47. }
  48. /*
  49. * disk usage of path/disk
  50. */
  51. //func DiskUsage(path string) map[string]string {
  52. // mDisk := make(map[string]string)
  53. // sFs := syscall.Statfs_t{}
  54. // Err := syscall.Statfs(path, &sFs)
  55. // if Err != nil {
  56. // log.Println("ERROR", "170060|查询磁盘使用情况出错", Err.Error())
  57. // return mDisk
  58. // }
  59. // All := sFs.Blocks * uint64(sFs.Bsize) / 1024 / 1024
  60. // Free := sFs.Bfree * uint64(sFs.Bsize) / 1024 / 1024
  61. // mDisk["All"] = strconv.FormatUint(All, 10)
  62. // mDisk["Free"] = strconv.FormatUint(Free, 10)
  63. // mDisk["Used"] = strconv.FormatUint((All - Free), 10)
  64. // return mDisk
  65. //}
  66. //func MemStat() map[string]string {
  67. // //系统占用,仅linux/mac下有效
  68. // //system memory usage
  69. // mMem := make(map[string]string)
  70. // sysInfo := new(syscall.Sysinfo_t)
  71. // Err := syscall.Sysinfo(sysInfo)
  72. // if Err == nil {
  73. // All := sysInfo.Totalram / 1024 / 1024
  74. // Free := sysInfo.Freeram / 1024 / 1024
  75. // Swap := sysInfo.Totalswap / 1024 / 1024
  76. // SwapFree := sysInfo.Freeswap / 1024 / 1024
  77. // mMem["All"] = strconv.FormatUint(All, 10) //* uint64(syscall.Getpagesize())
  78. // mMem["Free"] = strconv.FormatUint(Free, 10) //* uint64(syscall.Getpagesize())
  79. // mMem["Used"] = strconv.FormatUint(All-Free, 10)
  80. // mMem["Swap"] = strconv.FormatUint(Swap, 10)
  81. // mMem["SwapFree"] = strconv.FormatUint(SwapFree, 10)
  82. // mMem["SwapUsed"] = strconv.FormatUint(Swap-SwapFree, 10)
  83. // day := sysInfo.Uptime / 86400
  84. // hour := sysInfo.Uptime % 86400 / 3600
  85. // minute := sysInfo.Uptime % 86400 % 3600 / 60
  86. // tTime := time.Now().Unix() - sysInfo.Uptime
  87. // tNow := time.Unix(tTime, 10)
  88. // mMem["StartTime"] = tNow.Format("2006") + "-" + tNow.Format("01") + "-" + tNow.Format("02") + " " + tNow.Format("15") + ":" + tNow.Format("04") + ":" + tNow.Format("05")
  89. // mMem["Runtime"] = strconv.FormatInt(day, 10) + "天" + strconv.FormatInt(hour, 10) + "小时" + strconv.FormatInt(minute, 10) + "分钟"
  90. //
  91. // } else {
  92. // log.Println("ERROR", "170060|查询内存使用情况出错", Err.Error())
  93. // }
  94. // return mMem
  95. //}
  96. /**
  97. * IO读写
  98. */
  99. func IoUsage() map[string]string {
  100. cmd := exec.Command("iostat")
  101. var out bytes.Buffer
  102. cmd.Stdout = &out
  103. err := cmd.Run()
  104. mIo := make(map[string]string)
  105. if err != nil {
  106. log.Println("ERROR", "170061|系统命令iostat 执行错误", err.Error())
  107. return mIo
  108. }
  109. for {
  110. line, err := out.ReadString('\n')
  111. if err != nil {
  112. break
  113. }
  114. tokens := strings.Split(line, " ")
  115. ft := make([]string, 0)
  116. for _, t := range tokens {
  117. if t != "" && t != "\t" {
  118. fi := strings.Trim(t, "\n\t")
  119. ft = append(ft, fi)
  120. }
  121. }
  122. if ft[0] == "sda" {
  123. mIo["ReadSpd"] = ft[2]
  124. mIo["WriteSpd"] = ft[3]
  125. mIo["Read"] = ft[4]
  126. mIo["Write"] = ft[5]
  127. }
  128. }
  129. return mIo
  130. }
  131. /**
  132. *文件系统使用率
  133. */
  134. func FileUsage() []interface{} {
  135. cmd := exec.Command("df", "-h")
  136. var out bytes.Buffer
  137. cmd.Stdout = &out
  138. err := cmd.Run()
  139. mList := make([]interface{}, 0)
  140. if err != nil {
  141. log.Println("ERROR", "170061|系统命令df -h执行错误", err.Error())
  142. return mList
  143. }
  144. var mRet map[string]string
  145. for {
  146. line, err := out.ReadString('\n')
  147. if err != nil {
  148. break
  149. }
  150. tokens := strings.Split(line, " ")
  151. ft := make([]string, 0)
  152. for _, t := range tokens {
  153. if t != "" && t != "\t" {
  154. fi := strings.Trim(t, "\n\t")
  155. ft = append(ft, fi)
  156. }
  157. }
  158. if ft[0] != "Filesystem" {
  159. mRet = make(map[string]string)
  160. mRet["FileSystem"] = ft[0]
  161. mRet["All"] = ft[1]
  162. mRet["Used"] = ft[2]
  163. mRet["Free"] = ft[3]
  164. mRet["UsePercent"] = ft[4]
  165. mRet["Mounted"] = ft[5]
  166. mList = append(mList, mRet)
  167. }
  168. }
  169. return mList
  170. }
  171. /**
  172. *系统负载1 5 10 分钟
  173. */
  174. func LoadAverage() map[string]string {
  175. cmd := exec.Command("uptime")
  176. var out bytes.Buffer
  177. cmd.Stdout = &out
  178. err := cmd.Run()
  179. mRet := make(map[string]string)
  180. if err != nil {
  181. log.Println("ERROR", "170061|系统命令uptime执行错误", err.Error())
  182. return mRet
  183. }
  184. sLine, err := out.ReadString('\n')
  185. if err != nil {
  186. log.Println("ERROR", "170060|读取系统负载数据出错", err.Error())
  187. return mRet
  188. }
  189. //正则表达获取1 5 15 分钟系统负载数据
  190. sRegs := "\\d+\\.\\d+"
  191. sReg := regexp.MustCompile(sRegs)
  192. sLoadAverage := sReg.FindAllString(sLine, 3)
  193. if len(sLoadAverage) >= 3 {
  194. mRet["OneMin"] = sLoadAverage[0]
  195. mRet["FivMin"] = sLoadAverage[1]
  196. mRet["TenfivMin"] = sLoadAverage[2]
  197. } else {
  198. return mRet
  199. }
  200. return mRet
  201. }
  202. /**
  203. *网卡使用情况
  204. */
  205. func NetUsage() []interface{} {
  206. var Net struct {
  207. NetCard string
  208. Rbytes string
  209. Rpackets string
  210. Rerrors string
  211. Rpck string
  212. Sbytes string
  213. Spackets string
  214. Serrors string
  215. Spck string
  216. }
  217. cmd := exec.Command("ifconfig")
  218. var out bytes.Buffer
  219. cmd.Stdout = &out
  220. err := cmd.Run()
  221. aNetList := make([]interface{}, 0)
  222. if err != nil {
  223. log.Println("ERROR", "170060|查询网卡使用情况出错", err.Error())
  224. return aNetList
  225. }
  226. for {
  227. line, err := out.ReadString('\n')
  228. if err != nil {
  229. break
  230. }
  231. tokens := strings.Split(line, " ")
  232. ft := make([]string, 0)
  233. for _, t := range tokens {
  234. if t != "" && t != "\t" {
  235. fi := strings.Trim(t, "\n\t")
  236. ft = append(ft, fi)
  237. }
  238. }
  239. if ft[0] != "" {
  240. if ft[1] == "Link" {
  241. Net.NetCard = ft[0]
  242. sPck := NetBytes(ft[0])
  243. if len(sPck) >= 2 {
  244. Net.Rpck = sPck[0]
  245. Net.Spck = sPck[1]
  246. } else {
  247. Net.Rpck = "0.0"
  248. Net.Spck = "0.0"
  249. }
  250. }
  251. if ft[0] == "RX" {
  252. if strings.Contains(ft[1], "packets") {
  253. sPackets := strings.SplitAfter(ft[1], ":")
  254. Net.Rpackets = sPackets[1]
  255. sErrors := strings.SplitAfter(ft[2], ":")
  256. Net.Rerrors = sErrors[1]
  257. }
  258. if strings.Contains(ft[1], "bytes") {
  259. rBytes := strings.SplitAfter(ft[1], ":")
  260. Net.Rbytes = rBytes[1]
  261. sBytes := strings.SplitAfter(ft[5], ":")
  262. Net.Sbytes = sBytes[1]
  263. aNetList = append(aNetList, Net)
  264. }
  265. }
  266. if ft[0] == "TX" {
  267. if strings.Contains(ft[1], "packets") {
  268. sPackets := strings.SplitAfter(ft[1], ":")
  269. Net.Spackets = sPackets[1]
  270. sErrors := strings.SplitAfter(ft[2], ":")
  271. Net.Serrors = sErrors[1]
  272. }
  273. }
  274. }
  275. }
  276. return aNetList
  277. }
  278. /**
  279. *网卡实时流量
  280. */
  281. func NetBytes(Iface string) []string {
  282. aBytesInfo := make([]string, 0)
  283. cmd := exec.Command("sar", "-n", "DEV", "1", "1")
  284. var out bytes.Buffer
  285. cmd.Stdout = &out
  286. err := cmd.Run()
  287. if err != nil {
  288. log.Println("ERROR", "170060|查询实时流量情况出错", err.Error())
  289. return aBytesInfo
  290. }
  291. for {
  292. line, err := out.ReadString('\n')
  293. if err != nil {
  294. break
  295. }
  296. tokens := strings.Split(line, " ")
  297. ft := make([]string, 0)
  298. for _, t := range tokens {
  299. if t != "" && t != "\t" {
  300. fi := strings.Trim(t, "\n\t")
  301. ft = append(ft, fi)
  302. }
  303. }
  304. if ft[0] == "Average:" {
  305. if ft[1] == Iface {
  306. aBytesInfo = append(aBytesInfo, ft[2])
  307. aBytesInfo = append(aBytesInfo, ft[3])
  308. }
  309. }
  310. }
  311. return aBytesInfo
  312. }
  313. /**
  314. *网络配置
  315. */
  316. func GetNetConfig() []interface{} {
  317. aNetCard := make([]interface{}, 0)
  318. cmd := exec.Command("cat", "/etc/network/interfaces")
  319. var out bytes.Buffer
  320. cmd.Stdout = &out
  321. err := cmd.Run()
  322. if err != nil {
  323. log.Println("ERROR", "170050|查询网卡配置信息出错", err.Error())
  324. return aNetCard
  325. }
  326. var mNetConfig map[string]string
  327. mNetConfig = make(map[string]string)
  328. for {
  329. line, err := out.ReadString('\n')
  330. if err != nil {
  331. break
  332. }
  333. nline := strings.Replace(line, "\t", " ", -1)
  334. tokens := strings.Split(nline, " ")
  335. ft := make([]string, 0)
  336. for _, t := range tokens {
  337. if t != "" {
  338. fi := strings.Trim(t, "\n")
  339. ft = append(ft, fi)
  340. }
  341. }
  342. switch ft[0] {
  343. case "auto":
  344. if len(ft) < 2 {
  345. ft = append(ft, " ")
  346. }
  347. if ft[1] != "lo" {
  348. mNetConfig["NetCard"] = ft[1]
  349. }
  350. case "netmask":
  351. if len(ft) < 2 {
  352. ft = append(ft, " ")
  353. }
  354. mNetConfig["NetMask"] = ft[1]
  355. case "gateway":
  356. if len(ft) < 2 {
  357. ft = append(ft, " ")
  358. }
  359. mNetConfig["GateWay"] = ft[1]
  360. case "address":
  361. if len(ft) < 2 {
  362. ft = append(ft, " ")
  363. }
  364. mNetConfig["Ip"] = ft[1]
  365. case "dns-nameservers":
  366. if len(ft) < 2 {
  367. ft = append(ft, "")
  368. }
  369. mNetConfig["Dns"] = ft[1]
  370. case "dns-nameserver":
  371. if len(ft) < 2 {
  372. ft = append(ft, "")
  373. }
  374. mNetConfig["Dns"] = ft[1]
  375. }
  376. if len(mNetConfig) == 5 {
  377. aNetCard = append(aNetCard, mNetConfig)
  378. mNetConfig = make(map[string]string)
  379. }
  380. }
  381. return aNetCard
  382. }
  383. /**
  384. *修改网络配置
  385. */
  386. func PutNetConfig(mString map[string]string) error {
  387. bFile, err := ioutil.ReadFile("/etc/network/interfaces")
  388. if err != nil {
  389. log.Println("ERROR", "170050|读取网卡配置文件出错", err.Error())
  390. return err
  391. }
  392. var sName, sRegs string
  393. var Reg *regexp.Regexp
  394. mNetCard := make(map[string]string, 0)
  395. for i, v := range mString {
  396. var err error
  397. if v == "" {
  398. err = errors.New("参数值为空")
  399. return err
  400. }
  401. switch i {
  402. case "Ip":
  403. mNetCard["address"] = v
  404. case "GateWay":
  405. mNetCard["gateway"] = v
  406. case "Dns":
  407. mNetCard["dns-nameserver"] = v
  408. case "NetMask":
  409. mNetCard["netmask"] = v
  410. }
  411. }
  412. for i, v := range mNetCard {
  413. sName = i
  414. sRegs = sName + "\\s+\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"
  415. Reg = regexp.MustCompile(sRegs)
  416. bOld := Reg.Find(bFile)
  417. bFile = bytes.Replace(bFile, bOld, []byte(i+" "+v), 1)
  418. }
  419. err = ioutil.WriteFile("/etc/network/interfaces", bFile, 644)
  420. if err != nil {
  421. panic(err)
  422. log.Println("ERROR", "170051|写入网卡配置文件出错", err.Error())
  423. return err
  424. }
  425. return nil
  426. }