Operations 6 min read

How to Check and Fix Linux File Permissions with Go

This article explains why proper file permissions and ownership are crucial for Linux security and provides a step‑by‑step Go implementation that reads file metadata, validates and corrects owners and modes, includes full example code, and discusses integration tips and required privileges.

Ops Development & AI Practice
Ops Development & AI Practice
Ops Development & AI Practice
How to Check and Fix Linux File Permissions with Go

Managing file permissions and owners is a key part of Linux system security; incorrect settings can lead to unauthorized access or data loss. The article introduces a Go‑based utility that automates checking and fixing these attributes.

1. Go for System‑Level Operations

Go’s concise syntax and extensive standard library, especially the os and os/user packages, make it well suited for system programming tasks such as creating, deleting, and managing file attributes.

2. Importance of Permissions and Ownership

Linux file permissions define read, write, and execute rights, while each file is associated with an owner and a group. Proper configuration protects system data from leaks and unauthorized modifications.

3. Implementing the Check‑and‑Fix Function

Read file status : Use os.Stat to obtain current mode and ownership.

Validate and fix owner : Look up the desired user with os/user, compare with the file’s UID/GID, and call os.Chown if they differ.

Validate and fix permissions : Compare the file’s mode with the expected mode and adjust using os.Chmod when necessary.

4. Example Code

package main

import (
    "fmt"
    "os"
    "os/user"
    "strconv"
    "golang.org/x/sys/unix"
)

func GetUidAndGid(u string) (int, int, error) {
    // Get user info by name
    userInfo, err := user.Lookup(u)
    if err != nil {
        return 0, 0, err
    }
    uid, err := strconv.Atoi(userInfo.Uid)
    if err != nil {
        return 0, 0, err
    }
    gid, err := strconv.Atoi(userInfo.Gid)
    if err != nil {
        return 0, 0, err
    }
    return uid, gid, nil
}

func checkAndFixFilePermissions(filePath, expectedUser, expectedPermissions string) error {
    fileInfo, err := os.Stat(filePath)
    if err != nil {
        return fmt.Errorf("failed to get file info: %v", err)
    }

    uid, gid, err := GetUidAndGid(expectedUser)
    if err != nil {
        return fmt.Errorf("get user info error: %v", err)
    }
    var stat unix.Stat_t
    err = unix.Stat(filePath, &stat)
    if err != nil {
        return err
    }
    if stat.Uid != uint32(uid) || stat.Gid != uint32(gid) {
        if err := os.Chown(filePath, uid, gid); err != nil {
            return fmt.Errorf("failed to change file owner: %v", err)
        }
    }

    expectedPerm, err := strconv.ParseUint(expectedPermissions, 8, 32)
    if err != nil {
        return fmt.Errorf("failed to parse permissions: %v", err)
    }
    if fileInfo.Mode().Perm() != os.FileMode(expectedPerm) {
        if err := os.Chmod(filePath, os.FileMode(expectedPerm)); err != nil {
            return fmt.Errorf("failed to change file permissions: %v", err)
        }
    }
    return nil
}

func main() {
    // Example usage
    filePath := "/tmp/tmp.WL5RfROb94"
    expectedUser := "yijie"
    expectedPermissions := "0644"
    if err := checkAndFixFilePermissions(filePath, expectedUser, expectedPermissions); err != nil {
        fmt.Println("Error:", err)
    } else {
        fmt.Println("File check and fix completed")
    }
}

5. Practical Use and Caveats

The function can be integrated into larger monitoring or maintenance scripts to automate routine system‑admin tasks. When changing owners, the Go program must run with sufficient privileges (often root). Proper error handling and testing are essential to avoid unintended permission changes.

By leveraging Go’s powerful standard library and Linux’s flexible permission model, developers can reliably enforce security configurations and improve overall system stability.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

GolinuxFile Permissionsos.Chmodos.Chown
Ops Development & AI Practice
Written by

Ops Development & AI Practice

DevSecOps engineer sharing experiences and insights on AI, Web3, and Claude code development. Aims to help solve technical challenges, improve development efficiency, and grow through community interaction. Feel free to comment and discuss.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.