How to get the file system type for syscall.Mount() programmatically

假如想象 提交于 2020-07-08 06:26:53

问题


The function Linux syscall.Mount requires a file system type.

If you try to run it with the file system auto, like this:

func main(){
    if err := syscall.Mount("/dev/sda1", "/mnt1", "auto", 0, "w"); err != nil {
        log.Printf("Mount(\"%s\", \"%s\", \"auto\", 0, \"rw\")\n","/dev/sda1","/mnt1")
        log.Fatal(err)
    }
}

It will fail with no such device. It was already described here that Linux syscall.Mount just wraps mount(2), which doesn't itself support the concept of an "auto" fstype.

I know how to find it using bash:

root@ubuntu:~/go/src# blkid /dev/sda1
/dev/sda1: UUID="527c895c-864e-4f4c-8fba-460754181173" TYPE="ext4" PARTUUID="db5c2e63-01"

or

root@ubuntu:~/go/src# file -sL /dev/sda1
/dev/sda1: Linux rev 1.0 ext4 filesystem data, UUID=527c895c-864e-4f4c-8fba-460754181173 (needs journal recovery) (extents) (large files) (huge files)

In both cases you get the ext4 file system type.

Replacing auto with ext4 in Go will solve the problem, but what I am interested in is, how can I use Go to get the file system type of, for example, /dev/sda1?

Is there a function similar to blkid or file that can show the file system type of the device?


回答1:


Did you try using the package blkid ? It seems to work out of the box as it internally implements the blkid shell command underneath (see blkid.go#L101). You can just get the key name for the map returned from the Blkid() function and reuse it in your API

package main

import (
    "fmt"
    blkid "github.com/LDCS/qslinux/blkid"
)

func main() {
    rmap := blkid.Blkid(false)
    var key string
    var result *blkid.Blkiddata

    for key, result = range rmap {
        fmt.Printf("Devname: %q\n", key)
    }

    fmt.Printf("Uuid_=%q\n", result.Uuid_)
    fmt.Printf("Uuidsub_=%q\n", result.Uuidsub_)
    fmt.Printf("Type_=%q\n", result.Type_)
    fmt.Printf("Label_=%q\n", result.Label_)
    fmt.Printf("Parttype_=%q\n", result.Parttype_)
    fmt.Printf("Partuuid_=%q\n", result.Partuuid_)
    fmt.Printf("Partlabel_ =%q\n", result.Partlabel_)
}

The Blkiddata struct contains all the information as with the default Linux version

type Blkiddata struct {
    Devname_   string
    Uuid_      string
    Uuidsub_   string
    Type_      string
    Label_     string
    Parttype_  string
    Partuuid_  string
    Partlabel_ string
}

Just get the module using

go get github.com/LDCS/qslinux/blkid

It also implements the other family of Linux utils namely - df, dmidecode, etcfstab, etchosts, etcservice, etcshadow, etcuser, hp, md, nmap, parted, scsi, smartctl and tgtd. See module github.com/LDCS/qslinux



来源:https://stackoverflow.com/questions/62759448/how-to-get-the-file-system-type-for-syscall-mount-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!