百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

Linux基础知识之shell实现用户管理功能

ahcoder 2025-06-03 19:51 4 浏览

[root@k8s-master shell]# more usermanager.sh 
#! /bin/bash
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m'
init() {
  [ "$(id -u)" -ne 0 ] && echo -e "${RED} ERROR: need root primission.${NC}" && exit 1
  if [ -f /etc/os-release ]; then
        . /etc/os-release
        OS=$NAME 

        if [[ $OS == *"CentOS Linux"* ]]; then
        PACKAGE_MANAGER="yum"
        USER_ADD_CMD="useradd"
        GROUP_ADD_CMD="groupadd"

        elif  [[ $OS == *"Ubuntu"* ]] || [[ $OS == *"Debian"* ]]; then
        PCKAGE_MANAGER="apt"
        USER_ADD_CMD="adduser"
        GROUP_ADD_CMD="addgroup"

        else
                echo -e "${YELLOW}note: unknown linux release: $OS, use common command ${NC}"
                PCKAGE_MANAGER="apt"
                USER_ADD_CMD="useradd"
                GROUP_ADD_CMD="groupadd"
        fi
  else
        echo -e "{RED} ERROR: cannot check system os ${NC}" && exit 1
  fi
  echo -e "${GREEN} checked: ${OS}${NC}"
}
user_exists() {
        id "$1" &>/dev/null
        return $?
}

group_exists() {
    grep -q "^$1:" /etc/group
        return $? 

}

add_user() {
        read -p "username: " username

        user_exists "username" && echo -e "${RED} user exists ${NC}" && return 1

        read -p "homedir(default/home/$username): " homedir

        homedir=${homedir:-/home/$username}

        read -p "Shell(default/bin/bash): " usershell

        usershell=${usershell:-/bin/bash}

        read -p "password: " userpass

        if [[ PACKAGE_MANAGER == "apt" ]]; then
        $USER_ADD_CMD $username --home $homedir --shell $usershell

        echo "$username:$userpass"| chpasswd

        else
                $USER_ADD_CMD -m -d $homedir -s $usershell $username
                echo "$userpass" | passwd --stdin $username
        fi
        [ $? -eq 0 ] && echo -e "${GREEN} user create success ${NC}" || echo -e "${RED} user create failed ${NC}"

        read -p "add sudo permission? (y/n): " add_sudo
        [[ $add_sudo == [yY] ]] && set_sudo_permission "$username"

}

delete_user() {
        read -p "need delete username: " username
        user_exists "$username" || {  echo -e "{$RED} user not exists ${NC}"; return 1;}

        read -p "delete homedir? (y/n): " del_home
        [[ $del_home == [yY] ]] && userdel -r $username || userdel $username
        [ $? -eq 0 ] && echo -e "${GREEN} user deleted ${NC}"|| echo -e "${RED} delete user failed ${NC}"
}

modify_user() {
        read -p "need modify username: " username
        user_exists "$username" || {  echo -e "{$RED} user not exists ${NC}"; return 1;}
        echo -e "1.change homedir 2.modify shell 3.change usergroup 4.back"

        read -p "choice: " choice

        case $choice in 

        1)      
                read -p "new homedir: " new_home
                usermod -d $new_home $username  && echo -e "${GREEN} change success${NC}" || echo -e "${RED} change failed ${NC}"
                ;;

        2)      
                read -p "new shell: " new_shell
                usermod -s $new_shell $username && echo -e "${GREEN} change success${NC}" || echo -e "${RED} change failed ${NC}"
                ;;

        3)  
                read -p "new usergroup: " new_group
                if ! group_exists "$new_group"; then
                        read -p "group not exists,if or not create? (y/n): " create_group
                [[ $create_group == [yY] ]] && $GROUP_ADD_CMD $new_group || return 1
                fi
                usermod -g $new_group $username && echo -e "${GREEN} change success${NC}" || echo -e "${RED} change failed${NC}"
                ;;
        4) return 0 ;;
        *) ;;
        esac
}

list_users() {
        echo -e "${BLUE} system user: ${NC}"
        echo -e "${YELLOW} username homedir  Shell ${NC}"
        echo "-----------------------------------"
        awk -F: '$3>=1000 && $3 < 65534 {print $3,$1,$6,$7}' /etc/passwd|sort -n|while read uid username homedir shell; do
        echo -e "${GREEN}$uid $username $homedir $shell${NC}"
        done
        echo -e "\n${BLUE}user account: $(awk -F: '$3>=1000 && $3 < 65534 {count++} END {print count}' /etc/passwd)${NC}"
}
manage_group() {
        local action=$1
        if [ "$action" = "add" ]; then
                read -p "new group_name: " groupname
        group_exists "$groupname" && echo -e "${RED} group exists ${NC}" && return 1
        $GROUP_ADD_CMD $groupname

        else
                read -p "need del group: " groupname
                group_exists "$groupname" || { echo -e "${RED}group not exists${NC}"; return 1; }
                groupdel $groupname
        fi 

        [ $? -eq 0 ] && echo -e "${GREEN} operatation success${NC}" || echo -e "${RED} operatation failed${NC}"
}

change_password() {
        read -p "username: " username
        user_exists "$username" || {  echo -e "{$RED} user not exists ${NC}"; return 1;}

        read -p "new password: " userpass

        if [[ $PACKAGE_MANAGER == "apt" ]]; then
                echo "$username:$userpass"|chpasswd
        else
                echo "$userpass"| passwd --stdin $username
        fi

        [ $? -eq 0 ] && echo -e "${GREEN} passwd already changed ${NC}" || echo -e "${RED} password change failed ${NC}"

}

set_sudo_permission() {
        local username=$1
        if [ -z "$username" ]; then
                read -p "username: " username
                user_exists "$username" || { echo -e "${RED} user not exists ${NC}"; return 1; }
        fi

        if [[ $PACKAGE_MANAGER == "apt" ]]; then
                usermod -aG sudo $username
                grep -q "^wheel:" /etc/group && usermod -aG wheel $username
        else
                usermod -aG wheel $username
        fi

        read -p "allow null sudo? (y/n): " nopass
        if [[ $nopass == [yY] ]]; then
                echo "$username ALL=(ALL) NOPASSWOD:ALL" >> /etc/sudoers.d/$username
                chmod 0440 /etc/sudoers.d/$username 
        fi
        echo -e "${GREEN} sudo permission already set ${NC}"
}
show_user_info() {
        read -p "username(display all users): " username
        [ -z $username ] && { list_users; return 0; }
        user_exists "$username" || { echo -e "${RED} user not exists ${NC}"; return 1; }

        uid=$(id -u $username)
        gid=$(id -g $username)
        groups=$(id -nG $username)
        homedir=$( grep "^$username:" /etc/passwd | cut -d: -f6)
        shell=$(grep "^$username:" /etc/passwd | cut -d: -f7)

        groups $username | grep -qE "\b(sudo|wheel)\b" && sudo_status="${GREEN} already permiss${NC}"|| sudo_status="${RED} not permiss${NC}"
        grep -q "^$username:!!" /etc/shadow 2>/dev/null && account_status="${RED} already locked${NC}"|| account_status="${GREEN} normal ${NC}"

        echo -e "${BLUE} user info: ${NC}"
        echo -e "UID: $uid\nGID: $gid\nhomedir: $homedir\nShell: $shell\ngroup:$groups\n sudo: $sudo_status\n status: $account_status"

        echo -e "\n${BLUE} last login: ${NC}"
        lastlog -u $username

}

main() {
        init
        while true; do
        clear
        echo 
        echo -e "${BLUE}|------------------------------------------------------|${NC}"
        echo -e "${BLUE}|--------------${NC}--${GREEN}Linux User Manager System${NC}-------------${BLUE}|${NC}"
        echo -e "${BLUE}|------------------------------------------------------|${NC}"
        echo 
        echo -e " ${GREEN} [1]${NC} adduser ${GREEN}[2]${NC} deleteuser ${GREEN}[3]${NC} changeuser"
        echo -e " ${GREEN} [4]${NC} listusers ${GREEN}[5]${NC} addgroup ${GREEN}[6]${NC} deletegroup"
        echo -e " ${GREEN} [7]${NC} changepassword ${GREEN}[8]${NC} setsudo ${GREEN}[9]${NC} userinfo"
        echo -e " ${RED} [0] ${NC} exit system"
        read -p "please choice opratation [0-9]: " choice
        echo

        case $choice in 
        1) add_user ;;
        2) delete_user ;;
        3) modify_user ;;
        4) list_users ;;
        5) manage_group "add" ;;
        6) manage_group "del" ;;
        7) change_password ;;
        8) set_sudo_permission ;;
        9) show_user_info ;;
        0) clear; exit 0 ;;
        *) ;;
        esac

        read -p "please press enter key continue..." dummy
        done
}
main

相关推荐

当 Linux 根分区 (/) 已满时如何释放空间?

根分区(/)是Linux文件系统的核心,包含操作系统核心文件、配置文件、日志文件、缓存和用户数据等。当根分区满载时,系统可能出现无法写入新文件、应用程序崩溃甚至无法启动的情况。常见原因包括:「日志文件...

linux系统监控工具小神器:btop(linux网络监控工具)

top是大家常用的实时系统监控工具,今天给大家介绍一款非常酷炫的实时系统监控工具btop,用了之后你一定会爱上它!btop是一个高级的实时系统监控工具,它是传统top命令的现代替代品,提供了丰富...

又一全新恶意软件曝光!专门针对Windows、Linux 和 macOS 用户

近日,网络安全研究人员发现了一个利用“CheanaStealer”恶意软件的复杂网络钓鱼活动,该恶意软件是通过一个VPN钓鱼网站传播的。这次攻击的主要目标是各种操作系统的用户,包括Wind...

Java程序员必备的Linux命令全解析

Java程序员必备的Linux命令全解析作为一名Java开发者,除了精通Java语法和框架外,掌握一些基础的Linux命令也是十分必要的。这不仅能提高你的工作效率,还能让你更好地管理和部署Java应用...

Linux基础知识之shell实现用户管理功能

[root@k8s-mastershell]#moreusermanager.sh#!/bin/bashRED='\033[0;31m'GREEN='\033[...

惊艳!Linux 中迷人的 Shell 脚本工具

如果您是Linux操作系统爱好者或正在将自己定义为一个爱好者,那么与shell脚本交叉的路径是完全不可避免的。根据定义,shell脚本是设计用于在Unix/Linuxshell环境中执...

【shell编程】你的第一个sh脚本(shell脚本编程教程)

vimhello.sh#!/bin/bash#注释echo-e"HelloWorld!\a\n"exit0第一行#!/bin/bash,作用是宣告这个文件内的语...

linux之bash、sh和dash(linux里bash命令)

linux系统里有sh、bash、dash等多种shell的解释器命令,其中sh是shll的缩写,是linux系统默认的shell解释器,bash则是sh命令的增强版,dash则是从netbsd派生而...

14、linux命令-du(linux命令-s)

14、linux命令-du常用命令du-sh/*#显示指定目录下每个文件或目录的容量大小,并且以易读方式显示(常用)。du命令概述du命令作用是估计文件系统的磁盘已使用量,常用于查看文件或目录...

Manjaro Linux:属于我的Linux体验

从Debiantesting切换回Manjarotesting前端使用好久的Manjarotesting切换到了Debiantesting,就是因为有一些包只有deb版本,适配了Debia...

小狼毫 0.17.0 更新,解锁输入新姿势!

0.17.0版本(2025年5月17日发布)这次更新可不少东西呢!先把librime升级到1.13.1版本啦,也不知道这升级之后会带来啥新变化,用用就知道咯。之前老是出问题的托...

Kali Linux 初始配置(kali linux2019默认用户名和密码)

1.更新源&升级系统sudoaptupdate&&sudoaptupgrade-ysudoaptdist-upgrade-y作用:确保所有工具和系统补丁为最新,避免...

怎样利用锤子手机和讯飞手机输入法,让电脑动起来

在大家看来,老罗的发布会捧红了科大讯飞。小编当时就被老罗洗脑了,立刻下载了讯飞输入法体验了一番。后来小编突发奇想,我经常使用向日葵远程控制电脑,如果远程控制电脑时使用讯飞,能否在电脑上完成语音输入?或...

装好KALI之后,急需做的两个事情,更新源和添加输入法

每次当我们装完系统之后,突然发现很茫然,为什么要装这个系统?也就是说我们压根儿就不知道装这个系统是为了做什么。而且刚装好的系统体验起来,好像也并没有网上说的那么好。之前想做的种种操作现在也就不了了之了...

Linux 依赖问题“硬核”解决方案 | 技术

编者按:本文介绍了一些另类的暴力破解RPM和DEB软件包依赖关系的方法,对陷入依赖陷阱而不可自拔的人来说,有时候这也是一种绝地求生之路。至于说这样做是否合适,那就是一件见仁见智的事情了,不过这...