Home > Blockchain >  Go "Permission Denied" when trying to create a new backup config file inside /etc
Go "Permission Denied" when trying to create a new backup config file inside /etc

Time:03-24

I am writing APIs with functionalities to save backups of config files inside /etc.

    backupContents, openErr := os.ReadFile(path)
    if openErr == nil {
        t := time.Now()
        backupPath := path   "."   t.Format("2006-01-02")   ".bk"
        err := os.WriteFile(backupPath, backupContents, 0777)
        if err != nil {
            return err
        }

    }
    if openErr == nil || errors.Is(openErr, os.ErrNotExist) {
        file, err := os.Create(path)
        if err != nil {
            return err
        }
        defer file.Close()
        if _, err := file.Write(updated); err != nil { //update file
            return err
        }
    } else if openErr != nil {
        return openErr
    }
    return nil
}

However, I get the error open /etc/dhcpcd.conf.2022-03-24.bk: permission denied" I can write to /etc/dhcpcd.conf successfully in the same function as my API binaries run with root access, how come creating a new file in /etc has permission errors? I thought of umask though I think it is not the issue, my default umask was 0022 but I set it to 0000 instead to try, but got the same permission errors. I also tried to replace os.WriteFile with os.OpenFile (with os.O_RDWR|os.O_CREATE flags) or os.Create but get the same permission denied errors.

Here is the permission of the /etc folder: drwxr-xr-x 115 root root 4096 Mar 24 10:56

Please help, thanks a lot~~

CodePudding user response:

you are probably running the script with a user that is not root user. try running the script with root user or with sudo.

/etc dir requires root permissions for creating/removing/editing files

CodePudding user response:

You need root permission, run with sudo before the command to run the script or sudo su in bash to get root access.

  • Related