登录
首页 >  Golang >  Go问答

Go 中的 Os Exec Sudo 命令

来源:Golang技术栈

时间:2023-04-23 19:12:15 460浏览 收藏

欢迎各位小伙伴来到golang学习网,相聚于此都是缘哈哈哈!今天我给大家带来《Go 中的 Os Exec Sudo 命令》,这篇文章主要讲到golang等等知识,如果你对Golang相关的知识非常感兴趣或者正在自学,都可以关注我,我会持续更新相关文章!当然,有什么建议也欢迎在评论留言提出!一起学习!

问题内容

在熟悉 Go 和 goroutines 的过程中,我遇到了执行命令的障碍。这些命令的格式是:

sudo find /folder -type f | while read i; do sudo -S chmod 644 "$i"; done

使用从[How to execute system command in Golang with unknown arguments 中获取的](https://stackoverflow.com/questions/20437336/how-to-execute-system- command-in-golang-with-unknown-arguments)代码,我正在尝试执行此命令,但我相信由于第一个参数是 sudo,它没有执行,我可能是错的。我只有两个问题。

当这些命令无法运行时,我返回“退出状态 1”,有没有办法获得比我正在做的更详细的错误?问题二,为什么我会用这个脚本得到“退出状态 1”?不应该发生的事情是什么?

package main

import (
    "bufio"
    "fmt"
    "os"
    "os/exec"
    "strings"
    "sync"
)

func ExeCmd(cmd string, wg *sync.WaitGroup) {
    parts := strings.Fields(cmd)
    head := parts[0]
    // Head at this point is "sudo"
    parts = parts[1:len(parts)]
    out, err := exec.Command(head,parts...).Output()
    if err != nil {
        fmt.Printf("%s\n", err)
    }
    fmt.Printf("%s\n", out)
    wg.Done() // Signal to WaitGroup goroutine finished
}

func InArray(a []string, e string) bool {
    for _, x := range a {
        if x == e {
            return true
            fmt.Print("True")
        }
    }
    return false
}

func main() {
    exec.Command("sudo ls > /dev/null") // Get sudo password just once, doesn't seem to work with Go
    wg := new(sync.WaitGroup)
    reader := bufio.NewReader(os.Stdin)
    fdbslices := []string{"f", "d", "b", "files", "directories", "both"}
    commands := []string{}
    fdb := ""
    filep := ""
    dirp := ""

    // Grab Path
    fmt.Print("Path: ")
    findpath, _ := reader.ReadString('\n')
    findpath = strings.ToLower(strings.Trim(findpath, "\n"))

    // Grab Files, Directories, or Both
    for {
        fmt.Print("Files, Directories, or Both: ")
        fdb, _ = reader.ReadString('\n')
        fdb = strings.ToLower(strings.Trim(fdb, "\n"))
        if InArray(fdbslices, fdb) == true { break }
    }

    // Build commands string, these come out as they should
    for {
        if fdb == "f" || fdb == "files" {
            fmt.Print("Permissions for Files: ")
            filep, _ = reader.ReadString('\n')
            filep = strings.Trim(filep, "\n")
            commands = append(commands, "sudo find " + findpath + " -type f | while read i; do sudo -S chmod " + filep + " \"$i\"; done")
        }
        if fdb == "d" || fdb == "directories" {
            fmt.Print("Permissions for Directories: ")
            dirp, _ = reader.ReadString('\n')
            dirp = strings.Trim(dirp, "\n")
            commands = append(commands, "sudo find " + findpath + " -type d | while read i; do sudo -S chmod " + dirp + " \"$i\"; done")
        }
        if fdb == "b" || fdb == "both" {
            fmt.Print("Permissions for Files: ")
            filep, _ = reader.ReadString('\n')
            filep = strings.Trim(filep, "\n")
            commands = append(commands, "sudo find " + findpath + " -type f | while read i; do sudo -S chmod " + filep + " \"$i\"; done")
            fmt.Print("Permissions for Directories: ")
            dirp, _ = reader.ReadString('\n')
            dirp = strings.Trim(dirp, "\n")
            commands = append(commands, "sudo find " + findpath + " -type d | while read i; do sudo -S chmod " + dirp + " \"$i\"; done")
        }
        break
    }

    // Execute Commands
    for _, str := range commands {
        wg.Add(1)
        fmt.Print("Doing: " + str + "\r\n")
        go ExeCmd(str, wg)
    }

    wg.Wait()
}

示例终端输出:

Path: test
Files, Directories, or Both: b
Permissions for Files: 644
Permissions for Directories: 755
Doing: find test -type f | while read i; do sudo -S chmod 644 "$i"; done
Doing: find test -type d | while read i; do sudo -S chmod 755 "$i"; done
exit status 1

exit status 1

感谢您的时间。

正确答案

exec.Command()将要求内核直接执行给定的进程。但是,您传递的命令是由 shell 脚本连接在一起的多个程序的字符串。

如果你想执行一个 shell 脚本,你应该使用这样的东西:

cmd := exec.Command("/bin/sh", "-c", "sudo find ...")

本篇关于《Go 中的 Os Exec Sudo 命令》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:Golang技术栈 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>