码迷,mamicode.com
首页 > Windows程序 > 详细

golang执行Linux和Windows命令

时间:2019-10-03 14:21:12      阅读:282      评论:0      收藏:0      [点我收藏+]

标签:nil   str   gen   code   href   eric   tps   erro   result   

1. 可接收变参命令

package main
import (
    "fmt"   
    "os"
    "os/exec"
    "strings"
)

func main(){
    sliceFunc(os.Args[1:]...)
}

func sliceFunc(cmd... string){
    fmt.Println(cmd)
    if len(cmd) == 0 { 
        fmt.Printf("Usage: %s args...\n", os.Args[0])
        os.Exit(-1)
    }   
    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[0], cmd[1:]...).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: 2, value:[uname -a]
Linux e531 5.0.0-29-generic #31~18.04.1-Ubuntu SMP Thu Sep 12 18:29:21 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
$ go run slice.go uname 
[uname]
cmd slice len: 1, value:[uname]
Linux

2. Linux和Windows命令

只接收单个命令并执行:

package main

import (
    "fmt"
    "errors"
    "os"
    "os/exec"
    "runtime"
    "strings"
)

func main(){
    if len(os.Args) == 1{
        fmt.Printf("Usage: %s args...\n", os.Args[0])
        os.Exit(-1)
    }
    str1, err := RunCommandWithErr(os.Args[1])
    if err != nil {
        fmt.Println(err.Error())
    } else {
        fmt.Println(str1)    
    }

    str := RunCommand(os.Args[1])    
    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功能代码

golang执行Linux和Windows命令

标签:nil   str   gen   code   href   eric   tps   erro   result   

原文地址:https://www.cnblogs.com/embedded-linux/p/11619637.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!