golang执行linux命令

golang exec 执行系统命令
golang    2014-09-25 13:17:44    2779    0    0

exec.Command()

最简单的方法:

cmd := exec.Command("/bin/sh/", "-c", "linux命令")

或复杂的, 各个参数都要单独写

cmd := exec.Command("ls", "-l", "-a")

 

package main
   
import (
    "bytes"
    "fmt"
    "os/exec"
)
   
func main() {
    in := bytes.NewBuffer(nil)
    cmd := exec.Command("sh")
    cmd.Stdin = in
    go func() {
        in.WriteString("echo hello world > test.txt\n")
        in.WriteString("exit\n")
    }()
    if err := cmd.Run(); err != nil {
        fmt.Println(err)
        return
    }
}
posted @ 2016-08-31 15:40 黑手党老k 阅读(...) 评论(...) 编辑 收藏