簡體   English   中英

查看誰當前登錄並從/ etc / passwd獲取他們的信息

[英]See who is currently logged in and get their information from /etc/passwd

我希望能夠查看當前登錄到服務器的用戶,然后根據其用戶名搜索/etc/passwd文件,並找到其ID(column3)和全名(column5)並一起顯示。

例如:

$ who    
USER         TTY
billyt     pts/2 
$ cat /etc/passwd
…
billyt:x:10:100:Tom Billy:/home/billyt:/bin/bash
…

我的輸出應顯示他的用戶名,ID和全名:

Username: billyt   ID: 10   FullName: Tom Billy

這是我到目前為止嘗試過的:

#!/bin/bash
file="/etc/passwd"

while IFS=: read -r f1 f2 f3 f4 f5 f6 f7
do
        # display fields using f1, f2,..,f7
        echo "Username: $f1, UserID: $f3, FullName: $f5"
done <"$file"

我嘗試顯示所需的字段(f1,f3和f5)。 這是一個好方法嗎? 我能簡單地從who命令中搜索,將who(用戶名)的第一個字段保存到who.txt然后從上面的文件中搜索它嗎?

您可以通過who命令將用戶存儲在數組中,然后在讀取/etc/passwd文件時,遍歷該數組以查看該數組中是否存在該用戶,如果存在,則從/etc/passwd文件中打印條目以您想要的格式。

就像是:

#!/bin/bash

while read -r user throw_away; do 
    users+=( "$user" )
done < <(who)

while IFS=: read -r f1 f2 f3 f4 f5 f6; do
    for name in "${users[@]}"; do
        if [[ "$name" == "$f1" ]]; then
            echo "Username: $f1, UserID: $f3, FullName: $f5"
        fi
    done
done < /etc/passwd 

我們使用進程替換 <(..)who的輸出傳遞給first while loop並創建一個數組users 因為我們只需要名稱,所以我們使用一個偽變量throwaway來捕獲其他所有內容。

在第二個while loop (我重復使用了大多數現有代碼),我們檢查數組中是否存在`/ etc / passwd /文件的第一個字段。 如果是這樣,我們將以您希望的格式打印該行。

您還可以使用關聯數組(bash v4.0或更高版本)將用戶存儲為鍵。 我會把它留給您練習。

當然,有很多方法可以做到這一點。

echo "Username     UserID  Full Name"
while read name therest; do
  g=$(grep "$name" /etc/passwd)
  [[ "$g" =~ ([^:]+):[^:]+:([^:]+):[^:]+:([^:]+) ]]
  printf "%-12s %6d  %s\n" \
         "${BASH_REMATCH[1]}" \
         "${BASH_REMATCH[2]}" \
         "${BASH_REMATCH[3]}"
done < <(who)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM