shell脚本习题

本文提供了一系列的Shell脚本实例,包括检测网络活动IP、获取当前用户信息、批量创建用户并设置密码、检查运行服务、解析passwd文件、实现参数交互式输出、查找无密码用户、统计特定shell用户、监控磁盘使用率以及处理共享库文件等,旨在提升Shell脚本操作系统的管理水平。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.查找当前网段(10.1.1.0/24)内存活IP用户,重定向到/tmp/ip.txt文件中

ping -c 次数 -W 超时时间 IP
#!/bin/bash
ip=10.1.1.0/24
ip=${ip%.*}   #ip=10.1.1
for i in `seq 1 254`;do
(ping -c 1 -W 1 $ip.$i > /dev/null 2>&1
if [ $? -eq 0 ]; then
echo $ip.$i >> /tmp/ip.txt 
else
echo "$ip.$i is dead"
fi) &
done

2.打印当前用户的用户名,和uid
id -un 
id -u


3.自动创建用户student101-150,且密码为password101-150
#!/bin/bash
for i in `seq 101 150`; do
id student$i > /dev/null 2>&1
if [ $? -eq 0 ]; then
echo "user student$i exist"
else
useradd student$i 
echo "user student$i added"
echo "password$i" | passwd --stdin student$i > /dev/null 2>&1
fi
done


4.编写一个shell脚本,检测当前服务器正在运行的网络服务,并输出服务名
#!/bin/bash
netstat -tulnp | awk  -F'/' '/^tcp|^udp/{print $2}' | sort -u

5.根据/etc/passwd文件内容,输出“The line 1(行数) is root(用户名)”依次类推
awk -F: '{printf "The line %s is %s \n",NR,$1 }' /etc/passwd
#!/bin/bash
#shell
n=1
while read line;  do
user=${line%%:*}
echo "the line $n is $user"
let n++
done < /etc/passwd

6.创建一个shell脚本 /root/test6.sh 
--当你输入“kernel”参数时,此shell脚本就输出“user“   
--当你输入”user“参数时,此shell脚本就输出”kernel”
--当此脚本不输入任何参数或者输入的参数是按照要求输入的话,那么就会输出标准错误“usage:/root/program kernel|user
#!/bin/bash

case $1 in
kernel)
echo "user"
;;
user)
echo "kernel"
;;
*)
echo "Usage: $0 kernel|user"
exit 1
esac

7.打印无密码用户
awk -F: '$2 == "!!" || $2 =="**"{print $1}' /etc/shadow

8.写一个脚本,显示当前系统上shell为-s指定类型的shell,并统计其用户总数。-s选项后面跟的参数必须是/etc/shells文件中存在的shell类型,否则不执行此脚本。另外,此脚本还可以接受--help选项,以显示帮助信息。脚本执行形如:
./test8.sh -s /bin/bash
显示结果形如:
/bin/bash,3users,they are:
root,redhat,gentoo
#!/bin/bash
if [ $# -eq 2 ]; then
case $1 in 
-s)
flag=`grep "$2" /etc/shells`
if [ -n $flag ]; then
user_number=`grep "$2$" /etc/passwd | wc -l`
user_list=`grep "$2$" /etc/passwd | awk -F: '{print $1}' `
echo  "$2,${user_number}users,they are: "
echo $user_list
fi
;;
--help|-h)
echo "Usage: $0 -s SHELL_TYPE" 
;;
*)
echo "syntax error,use -h to get help"
exit 1
esac

else
echo "Error,missing parameter"
exit 1
fi

9.监控磁盘的使用率,>90%时给root发邮件
#!/bin/bash
df -P  | sed '1d' | while read line; do
usage=`echo $line | awk '{print $5}'` 
usage=${usage%\%}
disk=`echo $line | awk '{print $6}'`
if [ $usage -gt 90 ]; then
echo "$disk is in a high usage!" | mail -s "Warnning!!" root@localhost
fi
done
10.ldd是用来查看二进制程序的共享库文件的,现在通过脚本实现把库文件自动的复制到固定目录(/newroot)的相对应的目录中,如源库文件:/lib/a.so.1,应复制到/newroot/lib64/libtinfo.so.5

11.查看主机网卡流量,每2秒显示1次当前的速率(sleep 2程序睡眠2秒)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值