Golang执行命令chmod返回错误。

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

Golang exec command chmod returning error

问题

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

  1. func main() {
  2. cmd := exec.Command("chmod", "400", "*.pem")
  3. cmd.Stdout = os.Stdout
  4. cmd.Stderr = os.Stdout
  5. if err := cmd.Run(); err != nil {
  6. fmt.Println("错误:", err)
  7. }
  8. }

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

  1. chmod: 无法访问'*.pem': 没有那个文件或目录
  2. 错误: 退出状态 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 *

  1. func main() {
  2. cmd := exec.Command( "chmod", "400", "*.pem" )
  3. cmd.Stdout = os.Stdout
  4. cmd.Stderr = os.Stdout
  5. if err := cmd.Run(); err != nil {
  6. fmt.Println( "Error:", err )
  7. }

I keep get this error while executing:

  1. chmod: cannot access '*.pem': No such file or directory
  2. Error: exit status 1
  3. </details>
  4. # 答案1
  5. **得分**: 5
  6. C和其他语言中的“system”库调用不同,os/exec包有意不调用系统shell,也不展开任何通配符模式或处理其他扩展、管道或重定向,这通常是由shell完成的。
  7. 因此,在这里,`*`不会被展开。作为解决方法,你应该使用下面的代码来实现:
  8. ```go
  9. 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:

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

答案2

得分: 2

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

  1. filepath.WalkDir(".", func(filePath string, f fs.DirEntry, e error) error {
  2. if e != nil {
  3. log.Fatal(e)
  4. }
  5. if filepath.Ext(f.Name()) == ".pem" {
  6. err := os.Chmod(filePath, 0400)
  7. if err != nil {
  8. log.Fatal(err)
  9. }
  10. fmt.Println(fmt.Sprintf("成功更改文件权限,文件:%s", filePath))
  11. }
  12. return nil
  13. })

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

英文:

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

  1. filepath.WalkDir(&quot;.&quot;, func(filePath string, f fs.DirEntry, e error) error {
  2. if e != nil {
  3. log.Fatal(e)
  4. }
  5. if filepath.Ext(f.Name()) == &quot;.pem&quot; {
  6. err := os.Chmod(filePath, 0400)
  7. if err != nil {
  8. log.Fatal(err)
  9. }
  10. fmt.Println(fmt.Sprintf(&quot;Successfully changed file permission, file: %s&quot;, filePath))
  11. }
  12. return nil
  13. })

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:

确定