Golang获取linux登录用户信息

本文介绍了如何利用Go语言原生调用Linux的utmp结构体来读取系统中所有登录用户的详细信息。作者通过解析/var/run/utmp文件,实现了获取用户名、设备名和远程主机名的功能,并提供了相应的Go代码示例。经过测试验证,该方法能够有效获取登录用户数据。
摘要由CSDN通过智能技术生成

最近使用go获取Linux所有登录用户,运行额外进程(w|top)解析字符串方式不够方便,
因此找到原生调用方式,测试验证后记录下来

原理

Linux下登录的用户信息包含在/var/run/utmp文件下,每个用户为一个utmp结构体,读取并解析出所有用户.
参考 https://man7.org/linux/man-pages/man5/utmp.5.html

           #define UT_LINESIZE      32
           #define UT_NAMESIZE      32
           #define UT_HOSTSIZE     256

           struct exit_status {              /* Type for ut_exit, below */
               short e_termination;          /* Process termination status */
               short e_exit;                 /* Process exit status */
           };

           struct utmp {
               short   ut_type;              /* Type of record */
               pid_t   ut_pid;               /* PID of login process */
               char    ut_line[UT_LINESIZE]; /* Device name of tty - "/dev/" */
               char    ut_id[4];             /* Terminal name suffix,
                                                or inittab(5) ID */
               char    ut_user[UT_NAMESIZE]; /* Username */
               char    ut_host[UT_HOSTSIZE]; /* Hostname for remote login, or
                                                kernel version for run-level
                                                messages */
               struct  exit_status ut_exit;  /* Exit status of a process
                                                marked as DEAD_PROCESS; not
                                                used by Linux init(1) */
               /* The ut_session and ut_tv fields must be the same size when
                  compiled 32- and 64-bit.  This allows data files and shared
                  memory to be shared between 32- and 64-bit applications. */
           #if __WORDSIZE == 64 && defined __WORDSIZE_COMPAT32
               int32_t ut_session;           /* Session ID (getsid(2)),
                                                used for windowing */
               struct {
                   int32_t tv_sec;           /* Seconds */
                   int32_t tv_usec;          /* Microseconds */
               } ut_tv;                      /* Time entry was made */
           #else
                long   ut_session;           /* Session ID */
                struct timeval ut_tv;        /* Time entry was made */
           #endif

               int32_t ut_addr_v6[4];        /* Internet address of remote
                                                host; IPv4 address uses
                                                just ut_addr_v6[0] */
               char __unused[20];            /* Reserved for future use */
           };

Go代码

package main

import (
	"encoding/binary"
	"fmt"
	"io"
	"os"
)

const (
	UT_LINESIZE = 32
	UT_NAMESIZE = 32
	UT_HOSTSIZE = 256
)

type ExitStatus struct {
	Termination int16
	Exit        int16
}

type TimeVal struct {
	Sec  int32
	Usec int32
}

type Utmp struct {
	// https://man7.org/linux/man-pages/man5/utmp.5.html
	Type     int16             /* Type of record */
	_        [2]byte           /* 内存对齐,不可少*/
	Pid      int32             /* PID of login process */
	Device   [UT_LINESIZE]byte /* Device name of tty - "/dev/" */
	Id       [4]byte           /* Terminal name suffix, or inittab(5) ID */
	User     [UT_NAMESIZE]byte /* Username */
	Host     [UT_HOSTSIZE]byte /* Hostname for remote login, or kernel version for run-level messages */
	Exit     ExitStatus        /* Exit status of a process marked as DEAD_PROCESS; not used by Linux init(1) */
	Session  int32             /* Session ID (getsid(2)), used for windowing */
	Time     TimeVal           /* Time entry was made */
	AddrV6   [16]byte          /* Internet address of remote host; IPv4 address uses just ut_addr_v6[0] */
	Reserved [20]byte
}

func main() {
	f, err := os.Open("/var/run/utmp")
	if err != nil {
		panic("open /var/run/tmp failed: %s" + err.Error())
	}
	var utmps []*Utmp
	for {
		utmp := new(Utmp)
		err = binary.Read(f, binary.LittleEndian, utmp)
		if err == io.EOF {
			break
		} else if err != nil {
			panic("read /var/run/tmp failed: " + err.Error())
		}
		// #define USER_PROCESS	7	/* Normal process.  */
		if utmp.Type != 7 || utmp.User[0] == 0 {
			// 忽略特殊用户,参考 procps-ng/contrib/utmp.c 源码
			continue
		}
		utmps = append(utmps, utmp)
	}

	fmt.Printf("%s\t%s\t%s\n", "USER", "TTY", "FROM")
	for _, utmp := range utmps {
		fmt.Printf("%s\t%s\t%s\n", string(utmp.User[:]), string(utmp.Device[:]), string(utmp.Host[:]))
	}
}

测试验证

  1. 本机登录一个用户
  2. 通过ssh localhost 模拟再登录一个用户
  3. 查看wgo输出结果
    在这里插入图片描述
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值