golang执行Linux和Windows命令

时间:2021-07-14 14:44:45

1. 可接收变参命令

package main
import (
"fmt"
"os"
"os/exec"
"strings"
) func main(){
sliceFunc(os.Args[:]...)
} func sliceFunc(cmd... string){
fmt.Println(cmd)
if len(cmd) == {
fmt.Printf("Usage: %s args...\n", os.Args[])
os.Exit(-)
}
fmt.Println(cmdFunc(cmd...))
} func cmdFunc(cmd... string) string {
fmt.Printf("cmd slice len: %d, value:%v\n", len(cmd), cmd)
result, err := exec.Command(cmd[], cmd[:]...).Output()
if err != nil {
fmt.Println("Command failed:", err.Error())
} // return string(result) // with '\n'
return strings.TrimSpace(string(result))
}

执行结果:

$ go run slice.go uname -a
[uname -a]
cmd slice len: , value:[uname -a]
Linux e531 5.0.--generic #~18.04.-Ubuntu SMP Thu Sep :: UTC x86_64 x86_64 x86_64 GNU/Linux
$ go run slice.go uname
[uname]
cmd slice len: , value:[uname]
Linux

2. Linux和Windows命令

只接收单个命令并执行:

package main

import (
"fmt"
"errors"
"os"
"os/exec"
"runtime"
"strings"
) func main(){
if len(os.Args) == {
fmt.Printf("Usage: %s args...\n", os.Args[])
os.Exit(-)
}
str1, err := RunCommandWithErr(os.Args[])
if err != nil {
fmt.Println(err.Error())
} else {
fmt.Println(str1)
} str := RunCommand(os.Args[])
fmt.Println(str)
} func runInLinux(cmd string) string{
fmt.Println("Running Linux cmd:" , cmd)
result, err := exec.Command("/bin/sh", "-c", cmd).Output()
if err != nil {
fmt.Println(err.Error())
}
return strings.TrimSpace(string(result))
} func runInWindows(cmd string) string{
fmt.Println("Running Win cmd:", cmd)
result, err := exec.Command("cmd", "/c", cmd).Output()
if err != nil {
fmt.Println(err.Error())
}
return strings.TrimSpace(string(result))
} func RunCommand(cmd string) string{
if runtime.GOOS == "windows" {
return runInWindows(cmd)
} else {
return runInLinux(cmd)
}
} func RunLinuxCommand(cmd string) string{
if runtime.GOOS == "windows" {
return ""
} else {
return runInLinux(cmd)
}
} func runInLinuxWithErr(cmd string) (string, error) {
fmt.Println("Running Linux cmd:"+cmd)
result, err := exec.Command("/bin/sh", "-c", cmd).Output()
if err != nil {
fmt.Println(err.Error())
}
return strings.TrimSpace(string(result)), err
} func runInWindowsWithErr(cmd string) (string, error){
fmt.Println("Running Windows cmd:"+cmd)
result, err := exec.Command("cmd", "/c", cmd).Output()
if err != nil {
fmt.Println(err.Error())
}
return strings.TrimSpace(string(result)), err
} func RunCommandWithErr(cmd string) (string, error){
if runtime.GOOS == "windows" {
return runInWindowsWithErr(cmd)
} else {
return runInLinuxWithErr(cmd)
}
} func RunLinuxCommandWithErr(cmd string)(string, error){
if runtime.GOOS == "windows" {
return "", errors.New("could not run in Windows Os")
} else {
return runInLinuxWithErr(cmd)
}
}

执行结果:

$ go run cmd.go uname
Running Linux cmd:uname
Linux
Running Linux cmd: uname
Linux
$ go run cmd.go uname -a
Running Linux cmd:uname
Linux
Running Linux cmd: uname
Linux

参考:

1. golang功能代码

2. Go语言极速入门手册.go