簡體   English   中英

Bash腳本:在帳戶刪除過程中忽略刪除UNIX帳戶

[英]Bash scripting : Ignore deletion of unix accounts during account removal process

需要清除Linux機器上的用戶帳戶,幾乎沒有例外。 為我做同樣的腳本是

#UIDMAX will contain the minimum value used by OS for ID selection
UIDMIN=`grep "UID_MIN" /etc/login.defs`

#UIDMAX will contain the mixnimum value used by OS for ID selection
UIDMAX=`grep "UID_MAX" /etc/login.defs`

for i in  awk -F: -v "min=${UIDMIN##UID_MIN}" -v "max=${UIDMAX##UID_MAX}" '{ if ( $3 >= min && $3 <=max ) print $1}' /etc/passwd
do 
     userdel -r $i  
done

但是我想添加一些存儲在變量中的異常,在刪除用戶帳戶過程中腳本應忽略這些異常。 eg exceptions="test1 test2 test"我希望userdel在執行上述腳本的過程中忽略在exceptions變量中提到的用戶

為什么要使用awk?

# using lower-case variable names is conventional for things which are neither builtins
# nor environment variables to avoid namespace conflicts.
min=$(grep "^UID_MIN" /etc/login.defs); min=${min##*[[:space:]]}
max=$(grep "^UID_MAX" /etc/login.defs); max=${max##*[[:space:]]}

# set up an associative array of users to ignore
declare -A users_to_ignore=( [test1]=1 [test2]=1 [test]=1 )

while IFS=: read -r name _ pid _ <&3; do
  # check not only for pid min and max, but also presence in users_to_ignore
  if (( pid >= min && pid < max )) && ! [[ ${users_to_ignore[$name]} ]]; then
    userdel -r "$name"
  fi
done 3</etc/passwd

如果要在使用不同目錄源(NIS,LDAP等)的系統上工作,並且操作系統提供getent ,則可以使用3< <(getent passwd)而不是3</etc/passwd ; 這樣更靈活。


如果要支持bash的版本早於4.0,則可以使用:

users_to_ignore="test1 test2 test"

...和...

[[ " $users_to_ignore " =~ " $name " ]]

保持簡單,使用awk擅長(解析文本),並使用shell擅長(順序調用命令):

awk -F: -v exceptions="test1 test2 test" '
BEGIN {
    split(exceptions,tmp,/ /)
    for (i in tmp) {
        except[tmp[i]]
    }
}
NR==FNR {
   if ( sub(/UIDMIN/,"") ) min = $0
   if ( sub(/UIDMAX/,"") ) max = $0
   next
}
$3 >= min && $3 <=max && !($1 in except) {print $1}
' /etc/login.defs /etc/passwd |
while IFS= read -r name
do 
     userdel -r "$name"  
done

請注意,以上只是我嘗試翻譯您的命令,因為您沒有提供任何示例輸入和輸出,因此請在執行之前親自檢查一下。

暫無
暫無

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

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