版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fengfengdiandia/article/details/80070040
有时需要通过代码执行一些系统命令来获取信息,golang 提供exec.Command
来实现这一目的。
shtest.go
package main
import (
"fmt"
"os/exec"
"strings"
)
func exeSysCommand(cmdStr string) string {
cmd := exec.Command("sh", "-c", cmdStr)
opBytes, err := cmd.Output()
if err != nil {
fmt.Println(err)
return ""
}
return string(opBytes)
}
func GetLocalIp() string {
tmp := exeSysCommand("ifconfig eth0 | grep 'inet addr' | cut -d : -f 2 | cut -d ' ' -f 1")
if len(tmp) == 0 {
fmt.Println("GetLocalIp Failed")
return ""
}
localip := strings.Trim(tmp, "\n") // 去除尾部换行符
return localip
}
func main() {
ip := GetLocalIp()
fmt.Println("ip=", ip)
}
$ go run shtest.go
ip= 192.168.110.146