Skip to content

antony@notes:~/ops-automation$ cat "Ubuntu-Server-批次建立刪除使用者.md"

Ubuntu Server 批次建立刪除使用者

2022-08-18· ops-automation ·Shell Script

Ubuntu Server 批次建立刪除使用者

:::warning

:::spoiler 目錄

[TOC]

:::

mkuser

#!/bin/bash

[ "$#" != "1" ] && echo "請給一個數字,來說明要建幾個帳號!" && exit 1
[ -f /tmp/account.txt ] && rm /tmp/account.txt &>/dev/null && touch /tmp/account.txt

for ((i=1;i<=${1};i=i+1))
do
  if [ "${i}" -le "9" ]; then
    echo "user0${i}" >> /tmp/account.txt
  else
    echo "user${i}" >> /tmp/account.txt
  fi
done

# var
u=$(cat /tmp/account.txt)

while read n
do
  if cat /etc/passwd | grep "^$n" &>/dev/null; then
    echo "linux ${n} user 已存在"
  else
    sudo useradd -m -s /bin/bash $n &>/dev/null
    echo -e "${n}\n${n}" | sudo passwd $n &>/dev/null
    [ "$?" == "0" ] && echo "linux ${n} user ok"
  fi
  if hdfs dfs -ls /user | grep "$n" &>/dev/null; then
    echo "hdfs ${n} user 已存在"
  else
    hdfs dfs -mkdir /user/${n} &>/dev/null && hdfs dfs -chown ${n}:${n} /user/${n}
    [ "$?" == "0" ] && echo "hdfs ${n} user ok"
  fi
done < /tmp/account.txt

rmuser

#!/bin/bash

while read n
do
  if hdfs dfs -ls /user | grep "$n" &>/dev/null; then
    hdfs dfs -rm -r /user/${n} &>/dev/null && echo "hdfs ${n} user 刪除成功 !"
  else
    echo "hdfs ${n} user 不存在"
  fi
  if cat /etc/passwd | grep "^$n" &>/dev/null; then
    sudo userdel -r ${n} &>/dev/null && echo "linux ${n} user 刪除成功 !"
  else
    echo "linux ${n} user 不存在"
  fi
done < /tmp/account.txt