Golang exec 命令 chmod 返回错误
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( "Error:", err )
}
我在执行时一直收到这个错误:
chmod: cannot access '*.pem': No such file or directory
Error: exit status 1
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.
所以这里*
就不展开了。作为解决方法,您应该使用 next 使其工作:
cmd := exec.Command("sh", "-c", "chmod 400 *.pem" )
这是另一种使用 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("Successfully changed file permission, file: %s", filePath))
}
return nil
})
找到
在这里熟悉 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( "Error:", err )
}
我在执行时一直收到这个错误:
chmod: cannot access '*.pem': No such file or directory
Error: exit status 1
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.
所以这里*
就不展开了。作为解决方法,您应该使用 next 使其工作:
cmd := exec.Command("sh", "-c", "chmod 400 *.pem" )
这是另一种使用 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("Successfully changed file permission, file: %s", filePath))
}
return nil
})
找到