删除账户相关信息

功能需求
  1. 获取正确的待删除账户名
  2. 杀死系统中正在运行的属于该账户的进程
  3. 确认系统中属于该账户的所有文件
  4. 删除该账户
1. 获取正确的待删除账户名
shell 复制代码
#让用户输入账户名
read -t 10 -p "please input account name: " account

if [ -z $account ]
then
    echo "account name is empty"
    echo "exit script"
    exit
fi

#检查是否存在这个账户

account_info=$(cat < /etc/passwd | grep $account)
if [ $? -eq 1 ]
then
    echo "account "$account" not exist"
    echo "exit script"
    exit
fi

#账户存在
#确认是否要删除这个账户
echo "Is $account the user account"
echo $account_info
read -p "you wish to delete from the system?[y/n]: " isdel
case $isdel in
Y|y);;
*)
echo "exit script"
exit
;;
esac
2. 杀死系统中正在运行的属于该账户的进程

xargs 是一个强有力的命令,它能够捕获一个命令的输出,然后传递给另外一个命令.

之所以能用到这个命令,关键是由于很多命令不支持|管道来传递参数,而日常工作中有有这个必要,所以就有了 xargs 命令。

命令格式:

somecommand |xargs -item command

参数:

-d delim 分隔符

shell 复制代码
$ echo 'loop.sh
fileout
sedout' | xargs -d "\n" ls -l
-rw-rw-r-- 1 ubuntu ubuntu 32 Jun 12 20:09 fileout
-rwxrw-r-- 1 ubuntu ubuntu  0 Jun 13 18:04 loop.sh
-rw-rw-r-- 1 ubuntu ubuntu 22 Jun 21 12:53 sedout

由于ls 不支持管道,所以通过xargs将 echo 输出 fileout、loop.sh、sedout传给了 ls。下面开始处理属于用户的正在运行的进程。

1、先通过 ps -u 命令查找属于用户的进程

shell 复制代码
ps -u $account

2、将ps 的结果传给gawk,解析出pid

shell 复制代码
gawk '$1 ~ /[0-9]+/{print $1}' 

3、最后将pid列表通过xargs传给kill命令

shell 复制代码
xargs -d '\n' kill -9

合在一起:

shell 复制代码
ps -u $account | gawk '$1 ~ /[0-9]+/{print $1}' | xargs -d '\n' kill -9
3. 确认系统中属于该账户的所有文件
shell 复制代码
find / -user $account > $report_file
4. 删除该账户
shell 复制代码
userdel $account
5. 创建脚本
shell 复制代码
#!/usr/bin/bash

#让用户输入账户名
read -t 10 -p "please input account name: " account

if [ -z $account ]
then
    echo "account name is empty"
    echo "exit script"
    exit
fi

#检查是否存在这个账户

account_info=$(cat < /etc/passwd | grep $account)
if [ $? -eq 1 ]
then
    echo "account "$account" not exist"
    echo "exit script"
    exit
fi

#确认是否要删除这个账户
echo "Is $account the user account"
echo $account_info
read -p "you wish to delete from the system?[y/n]: " isdel
case $isdel in
Y|y);;
*)
echo "exit script"
exit
;;
esac

#查找正在运行的属于该账户的进程

ps -u $account | gawk '$1 ~ /[0-9]+/{print $1}' | xargs -d '\n' kill -9

#查找账户文件
find / -user $account > report_file

#删除账户
userdel $account
相关推荐
0xDevNull1 天前
Linux切换JDK版本详细教程
linux
进击的丸子1 天前
虹软人脸服务器版SDK(Linux/ARM Pro)多线程调用及性能优化
linux·数据库·后端
茶杯梦轩1 天前
从零起步学习RabbitMQ || 第二章:RabbitMQ 深入理解概念 Producer、Consumer、Exchange、Queue 与企业实战案例
服务器·后端·消息队列
甲鱼9292 天前
MySQL 实战手记:日志管理与主从复制搭建全指南
运维
Johny_Zhao3 天前
OpenClaw安装部署教程
linux·人工智能·ai·云计算·系统运维·openclaw
YuMiao3 天前
gstatic连接问题导致Google Gemini / Studio页面乱码或图标缺失问题
服务器·网络协议
chlk1234 天前
Linux文件权限完全图解:读懂 ls -l 和 chmod 755 背后的秘密
linux·操作系统
舒一笑4 天前
Ubuntu系统安装CodeX出现问题
linux·后端
改一下配置文件4 天前
Ubuntu24.04安装NVIDIA驱动完整指南(含Secure Boot解决方案)
linux
碳基沙盒4 天前
OpenClaw 多 Agent 配置实战指南
运维