Golang执行命令chmod返回错误。

huangapple go评论74阅读模式
英文:

Golang exec command chmod returning error

问题

熟悉一下Golang,我正在尝试执行shell命令,我需要对任何.pem文件进行chmod操作,所以我决定使用通配符*。

func main() {

    cmd := exec.Command("chmod", "400", "*.pem")

    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stdout

    if err := cmd.Run(); err != nil {
        fmt.Println("错误:", err)
    }
}

在执行时,我一直遇到这个错误:

chmod: 无法访问'*.pem': 没有那个文件或目录
错误: 退出状态 1
英文:

Familiarizing myself with Golang here and i am trying to execute shell commands, i need to chmod for any .pem file so i decided to use the wildcard *

func main() {

    cmd := exec.Command( "chmod", "400", "*.pem" )

    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stdout

    if err := cmd.Run(); err != nil {
        fmt.Println( "Error:", err )
    }

I keep get this error while executing:

chmod: cannot access '*.pem': No such file or directory
Error: exit status 1


</details>


# 答案1
**得分**: 5

与C和其他语言中的“system”库调用不同,os/exec包有意不调用系统shell,也不展开任何通配符模式或处理其他扩展、管道或重定向,这通常是由shell完成的。

因此,在这里,`*`不会被展开。作为解决方法,你应该使用下面的代码来实现:

```go
cmd := exec.Command("sh", "-c", "chmod 400 *.pem")
英文:

> Unlike the "system" library call from C and other languages, the os/exec package intentionally does not invoke the system shell and does not expand any glob patterns or handle other expansions, pipelines, or redirections typically done by shells.

So here, * will not be expanded. As a workaround, you should use next to make it work:

cmd := exec.Command(&quot;sh&quot;, &quot;-c&quot;, &quot;chmod 400 *.pem&quot; )

答案2

得分: 2

以下是使用os包更改文件权限的另一种方法:

filepath.WalkDir(".", func(filePath string, f fs.DirEntry, e error) error {
	if e != nil {
		log.Fatal(e)
	}
	if filepath.Ext(f.Name()) == ".pem" {
		err := os.Chmod(filePath, 0400)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(fmt.Sprintf("成功更改文件权限,文件:%s", filePath))
	}
	return nil
})

完整的代码可以在 https://play.golang.org/p/x_3WsYg4t52 找到。

英文:

Here is another approach to change a file permission using os package

filepath.WalkDir(&quot;.&quot;, func(filePath string, f fs.DirEntry, e error) error {
	if e != nil {
		log.Fatal(e)
	}
	if filepath.Ext(f.Name()) == &quot;.pem&quot; {
		err := os.Chmod(filePath, 0400)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(fmt.Sprintf(&quot;Successfully changed file permission, file: %s&quot;, filePath))
	}
	return nil
})

Complete code can be found at https://play.golang.org/p/x_3WsYg4t52

huangapple
  • 本文由 发表于 2021年8月10日 17:38:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/68724421.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定