Shell 脚本编程练习
- 1、查看有多少远程的 IP 在连接本机
- 2、对 100 以内的所有正整数相加求和(1+2+3+4...+100)
- 3、统计 13:30 到 14:30 所有访问 apache 服务器的请求有多少个
- 4、打印国际象棋棋盘
- 5、统计 13:30 到 14:30 所有访问本机 Aapche 服务器的远程 IP 地址是什么
- 6、统计每个远程 IP 访问了本机 apache 几次
- 7、创建 Linux 系统账户及密码
- 7、按时间对相关 log 信息进行备份脚本
- 8、监控内存和磁盘容量,小于给定值时报警
- 9、猜数字游戏
- 10、检测本机当前用户是否为超级管理员
- 11、编写脚本:提示用户输入用户名和密码
- 12、输入三个数并进行升序排序
- 13、判断输入字符是否为数字(浮点数、偶数还是奇数)
- 13、判断输入字符是否为整数
- 14、判断输入字符是否为整数(第二种方法)
- 15、判断输入字符是否为整数(第三种方法)
- 15、判断输入字符是否为整数(第四种方法)
- 16、剪刀石头布游戏(The Game of Scissors/Rock/Paper)
- 17、编写脚本测试 192.168.4.0/24 整个网段中哪些主机处于开机状态,哪些主机处于关机状态(for 版本)
- 18、编写脚本测试 192.168.4.0/24 整个网段中哪些主机处于开机状态,哪些主机处于关机状态(while 版本)
- 19、编写脚本测试 192.168.4.0/24 整个网段中哪些主机处于开机状态,哪些主机处于关机状态(多进程版)
- 20、打印九九乘法表
- 21、使用死循环实时显示 enp1s0 网卡发送的数据包流量
- 22、使用 user.txt 文件中的人员名单,在计算机中自动创建对应的账户并配置初始密码本脚本执行,需要提前准备一个 user.txt 文件,该文件中包含有若干用户名信息
- 23、编写批量修改扩展名脚本
- 24、使用 expect 工具自动交互密码远程其他主机安装 httpd 软件
- 25、一键部署 LNMP(源码安装版本)
- 26、100以内的正整数之和
- 27、任意正整数内的正整数之和
- 28、统计 13:30 到 14:30 所有访问 apache 服务器的请求有多少个
- 29、统计 13:30 到 14:30 所有访问本机 Aapche 服务器的远程 IP 地址是什么
- 30、统计每个远程 IP 访问了本机 apache 几次
- 31、统计当前 Linux 系统中可以登录计算机的账户有多少个
- 32、统计/var/log 有多少个文件,并显示这些文件名
- 33、判断/var/log目录下的每一个文件的内容类型,并统计普通文件的数量
- 34、将文件中所有的小写字母转换为大写字母
- 35、检查特定的软件包是否已经安装
- 36、监控 HTTP 服务器的状态(测试返回码)
- 37、自动添加防火墙规则,开启某些服务或端口(适用于 RHEL7)
- 38、使用脚本自动创建逻辑卷
- 39、显示 CPU 厂商信息
- 40、删除某个目录下大小为 0 的文件
- 41、查找 Linux 系统中的僵尸进程
- 42、提示用户输入年份后判断该年是否为闰年
- 43、生成随机密码(urandom 版本)
- 44、生成随机密码(字串截取版本)
- 45、生成随机密码(UUID 版本,16 进制密码)
- 46、生成随机密码(进程 ID 版本,数字密码)
- 47、生成随机密码(使用openssl rand工具)
- 48、测试用户名与密码是否正确
- 49、Shell 脚本的 fork 炸弹
- 50、批量下载有序文件(pdf、图片、视频等等)
- 51、显示当前计算机中所有账户的用户名称
- 52、打包备份某目录,指定目录路径,脚本自动将该目录使用 tar 命令打包备份到 /data 目录
- 53、编写一个脚本,找出172.16.141.X网络中哪些主机地址被使用,哪些未被使用,并把结果保存至相应的文件中
- 54、编写脚本,通过命令行参数传入一个用户名,判断ID是偶数还是奇数
- 55、安装 LAMP 环境(yum 版本)
- 56、循环关闭局域网中所有主机
- 57、计算当前系统上的所有用的id之和
- 58、非交互自动生成 SSH 密钥文件
- 59、检查特定的软件包是否已经安装
- 60、指定目录,进行压缩,并保存至 /data 目录下
- 61、显示主机上现在所有的监听端口
- 62、返回计算机当前时间,并返回问候语,可以设置为开机启动
1、查看有多少远程的 IP 在连接本机
#!/bin/bash
# 查看有多少远程的 IP 在连接本机(不管是通过 ssh 还是 web 还是 ftp 都统计)
# 使用 netstat ‐atn 可以查看本机所有连接的状态,‐a 查看所有,
# -t仅显示 tcp 连接的信息,‐n 数字格式显示
# Local Address(第四列是本机的 IP 和端口信息)
# Foreign Address(第五列是远程主机的 IP 和端口信息)
# 使用 awk 命令仅显示第 5 列数据,再显示第 1 列 IP 地址的信息
# sort 可以按数字大小排序,最后使用 uniq 将多余重复的删除,并统计重复的次数
netstat -atn | awk '{print $5}' | awk '{print $1}' | sort -nr | uniq -c
#!/bin/bash
# ss更执行速度更快
ss -tan | awk '{print $5}' | awk -F ":" '{print $1}' | sort -r | uniq -c
2、对 100 以内的所有正整数相加求和(1+2+3+4…+100)
#!/bin/bash
# 对 100 以内的所有正整数相加求和(1+2+3+4...+100)
#seq 100 可以快速自动生成 100 个整数
sum=0
for i in `seq 100`
do
sum=$[sum+i]
done
echo "总和是:$sum"
#!/bin/bash
declare -i sum=0
for i in {1..100}; do
# sum+=$i
sum=$[$sum+$i]
done
echo "1+2+3+...+100=$sum."
3、统计 13:30 到 14:30 所有访问 apache 服务器的请求有多少个
#!/bin/bash
# 统计 13:30 到 14:30 所有访问 apache 服务器的请求有多少个
# awk 使用‐F 选项指定文件内容的分隔符是/或者:
# 条件判断$7:$8 大于等于 13:30,并且要求,$7:$8 小于等于 14:30
# 最后使用 wc ‐l 统计这样的数据有多少行,即多少个
awk -F "[ /:]" '$7":"$8>="13:30" && $7":"$8<="14:30"' /var/log/httpd/access_log |wc -l
4、打印国际象棋棋盘
#!/bin/bash
# 打印国际象棋棋盘
# 设置两个变量,i 和 j,一个代表行,一个代表列,国际象棋为 8*8 棋盘
# i=1 是代表准备打印第一行棋盘,第 1 行棋盘有灰色和蓝色间隔输出,总共为 8 列
# i=1,j=1 代表第 1 行的第 1 列;i=2,j=3 代表第 2 行的第 3 列
# 棋盘的规律是 i+j 如果是偶数,就打印蓝色色块,如果是奇数就打印灰色色块
# 使用 echo ‐ne 打印色块,并且打印完成色块后不自动换行,在同一行继续输出其他色块
for i in {1..8}
do
for j in {1..8}
do
sum=$[i+j]
if [ $[sum%2] -eq 0 ];then
echo -ne "\033[46m \033[0m"
else
echo -ne "\033[47m \033[0m"
fi
done
echo
done
5、统计 13:30 到 14:30 所有访问本机 Aapche 服务器的远程 IP 地址是什么
#!/bin/bash
# 统计 13:30 到 14:30 所有访问 apache 服务器的请求有多少个
# awk 使用‐F 选项指定文件内容的分隔符是/或者:
# 条件判断$7:$8 大于等于 13:30,并且要求,$7:$8 小于等于 14:30
# 最后使用 wc ‐l 统计这样的数据有多少行,即多少个
awk -F "[ /:]" '$7":"$8>="13:30" && $7":"$8<="14:30"' /var/log/httpd/access_log |wc -l
6、统计每个远程 IP 访问了本机 apache 几次
#!/bin/bash
# 统计每个远程 IP 访问了本机 apache 几次?
awk '{ip[$1]++}END{for(i in ip){print ip[i],i}}' /var/log/httpd/access_log
7、创建 Linux 系统账户及密码
- 通过位置变量。输入用户名和密码
#!/bin/bash
# 通过位置变量创建 Linux 系统账户及密码
#$1 是执行脚本的第一个参数,$2 是执行脚本的第二个参数
useradd "$1"
echo "$2" | passwd ‐‐stdin "$1"
- 用户交互式,输入用户名和密码
[root@Tang-Neo ~]# cat adduserpasswd.sh
#!/bin/bash
#
read -p "Plz INPUT New User:" user
if id $user &> /dev/null; then
echo "The user $user exists."
exit 1
else
read -p "Plz INPUT The Password of $user:" passwd
useradd $user
echo "$passwd" | passwd --stdin "$user" &> /dev/null
fi
echo "The user $user add successfully."
echo "The Password of user $user is $passwd."
[root@Tang-Neo ~]# bash adduserpasswd.sh
Plz INPUT New User:test
Plz INPUT The Password of test:test
Creating mailbox file: File exists
The user test add successfully.
The Password of user test is test.
[root@Tang-Neo ~]# bash adduserpasswd.sh
Plz INPUT New User:test
The user test exists.
7、按时间对相关 log 信息进行备份脚本
[root@neo ~]# cat backup.sh
#!/bin/bash
# 编写备份脚本,备份后的文件名包含日期标签,防止后面的备份将前面的备份数据覆盖
# 注意 date 命令需要使用反引号括起来,反引号在键盘<tab>键上面
# 可配置 crontab 来进行定时任务设置,可直接写命令,也可写脚本
# 但是在指定脚本名称时,指定脚本具体路径,不然无法执行(因不在PATH环境变量中)
tar -zcf /var/log-`date +%Y%m%d-%H%M%s`.tar.gz /var/log/ &> /dev/null
8、监控内存和磁盘容量,小于给定值时报警
#!/bin/bash
# 实时监控本机内存和硬盘剩余空间,剩余内存小于500M、根分区剩余空间小于1000M时,发送报警邮件给root管理员
# 提取根分区剩余空间
disk_size=$(df / | awk '/\//{print $4}')
# 提取内存剩余空间
mem_size=$(free | awk '/Mem/{print $4}')
while :
do
# 注意内存和磁盘提取的空间大小都是以 Kb 为单位
if [ $disk_size -le 512000 -a $mem_size -le 1024000 ]
then
mail ‐s "Warning" root <<EOF
Insufficient resources,资源不足
EOF
fi
done
9、猜数字游戏
#!/bin/bash
# 脚本生成一个 100 以内的随机数,提示用户猜数字,根据用户的输入,提示用户猜对了,
# 猜小了或猜大了,直至用户猜对脚本结束。
# RANDOM 为系统自带的系统变量,值为 0‐32767的随机数
# 使用取余算法将随机数变为 1‐100 的随机数
num=$[RANDOM%100+1]
echo "$num" &> /dev/null
# 使用 read 提示用户猜数字
# 使用 if 判断用户猜数字的大小关系:‐eq(等于),‐ne(不等于),‐gt(大于),‐ge(大于等于),
# ‐lt(小于),‐le(小于等于)
while :
do
read -p "计算机生成了一个 1‐100 的随机数,你猜: " cai
if [ $cai -eq $num ]
then
echo "恭喜,猜对了"
exit
elif [ $cai -gt $num ]
then
echo "Oops,猜大了"
else
echo "Oops,猜小了"
fi
done
[root@neo ~]# bash bigORsmall.sh
计算机生成了一个 1‐100 的随机数,你猜: 22
Oops,猜小了
计算机生成了一个 1‐100 的随机数,你猜: 55
Oops,猜小了
计算机生成了一个 1‐100 的随机数,你猜: 77
Oops,猜大了
计算机生成了一个 1‐100 的随机数,你猜: 66
Oops,猜小了
计算机生成了一个 1‐100 的随机数,你猜: 70
Oops,猜大了
计算机生成了一个 1‐100 的随机数,你猜: 68
恭喜,猜对了
10、检测本机当前用户是否为超级管理员
#!/bin/bash
# 检测本机当前用户是否为超级管理员,如果是管理员,则使用 yum 安装 vsftpd,如果不
# 是,则提示您非管理员(使用字串对比版本)
if [ $USER == "root" ]
then
echo "您是管理员,有权限安装软件"
else
echo "您不是管理员,没有权限安装软件"
fi
[root@neo ~]# whoami
root
[root@neo ~]# bash /home/neo/rootYESorNO.sh
您是管理员,有权限安装软件
[neo@neo ~]$ whoami
neo
[neo@neo ~]$ bash rootYESorNO.sh
您不是管理员,没有权限安装软件
11、编写脚本:提示用户输入用户名和密码
编写脚本:提示用户输入用户名和密码,脚本自动创建相应的账户及配置密码。如果用户不输入账户名,则提示必须输入账户名并退出脚本;如果用户不输入密码,则统一使用默认的 123456 作为默认密码。
#!/bin/bash
# 编写脚本:提示用户输入用户名和密码,脚本自动创建相应的账户及配置密码。如果用户
# 不输入账户名,则提示必须输入账户名并退出脚本
# 如果用户不输入密码,则统一使用默认的 123456 作为默认密码
read -p "请输入用户名: " user
#使用‐z 可以判断一个变量是否为空,如果为空,提示用户必须输入账户名,并退出脚本,退出码为 2
#没有输入用户名脚本退出后,使用$?查看的返回码为 2
if [ -z $user ];then
echo "您不需输入账户名"
exit 2
fi
#使用 stty ‐echo 关闭 shell 的回显功能
#使用 stty echo 打开 shell 的回显功能
stty -echo
read -p "请输入密码: " pass
stty echo
pass=${pass:‐123456}
useradd "$user"
echo "$pass" | passwd ‐‐stdin "$user"
[root@neo ~]# cat uSERpasswd.sh
#!/bin/bash
#
read -p "Please Input Your Username:" user
if [ -z $user ]; then
echo -e "\e[1;31mYOU MUST TO INPUT NEW USERNAME!\e[0m"
exit 2
else
if id $user &> /dev/null ; then
echo -e "\e[1;31mTHE USER $user EXISTS!\e[0m"
echo -e "\e[1;31mYOU MUST TO INPUT ANOTHER NEW USERNAME!\e[0m"
exit 3
fi
fi
stty -echo
read -p "Please Input Your PASSWORD of $user:" pass
stty echo
pass=${pass:-123456}
useradd "$user"
echo "$pass" | passwd --stdin "$user" &> /dev/null
echo \n
echo "ADD $user SUCCESSFULLY!"
[root@neo ~]# bash uSERpasswd.sh
Please Input Your Username:newnewneo
Please Input Your PASSWORD of newnewneo:n
ADD newnewneo SUCCESSFULLY!
[root@neo ~]# bash uSERpasswd.sh
Please Input Your Username:newnewneo
THE USER newnewneo EXISTS!
YOU MUST TO INPUT ANOTHER NEW USERNAME!
12、输入三个数并进行升序排序
#!/bin/bash
# 依次提示用户输入 3 个整数,脚本根据数字大小依次排序输出 3 个数字
read -p "请输入一个整数:" num1
read -p "请输入一个整数:" num2
read -p "请输入一个整数:" num3
# 不管谁大谁小,最后都打印 echo "$num1,$num2,$num3"
# num1 中永远存最小的值,num2 中永远存中间值,num3 永远存最大值
# 如果输入的不是这样的顺序,则改变数的存储顺序,如:可以将 num1 和 num2 的值对调
tmp=0
# 如果 num1 大于 num2,就把 num1 和和 num2 的值对调,确保 num1 变量中存的是最小值
if [ $num1 -gt $num2 ];then
tmp=$num1
num1=$num2
num2=$tmp
fi
# 如果 num1 大于 num3,就把 num1 和 num3 对调,确保 num1 变量中存的是最小值
if [ $num1 -gt $num3 ];then
tmp=$num1
num1=$num3
num3=$tmp
fi
# 如果 num2 大于 num3,就把 num2 和 num3 对标,确保 num2 变量中存的是小一点的值
if [ $num2 -gt $num3 ];then
tmp=$num2
num2=$num3
num3=$tmp
fi
echo "排序后数据(从小到大)为:$num1,$num2,$num3"
[root@neo ~]# cat bigest.sh
#!/bin/bash
# 依次提示用户输入 3 个整数,脚本根据数字大小依次排序输出 3 个数字
# 定义函数 testnum 实现对输入内容的判断
testnum() {
if [ -z $1 ]; then
echo "请输入一个整数,不能为空!"
exit 2
else
if grep '^[[:digit:]]*$' <<< "$1" &> /dev/null;then
echo "你输入了整数:$1!" &> /dev/null
else
echo "请输入一个整数,不能是其它字符!"
exit 3
fi
fi
}
read -p "请输入一个整数:" num1
testnum $num1
read -p "请输入一个整数:" num2
testnum $num2
read -p "请输入一个整数:" num3
testnum $num3
# 不管谁大谁小,最后都打印 echo "$num1,$num2,$num3"
# num1 中永远存最小的值,num2 中永远存中间值,num3 永远存最大值
# 如果输入的不是这样的顺序,则改变数的存储顺序,如:可以将 num1 和 num2 的值对调
tmp=0
# 如果 num1 大于 num2,就把 num1 和和 num2 的值对调,确保 num1 变量中存的是最小值
if [ $num1 -gt $num2 ];then
tmp=$num1
num1=$num2
num2=$tmp
fi
# 如果 num1 大于 num3,就把 num1 和 num3 对调,确保 num1 变量中存的是最小值
if [ $num1 -gt $num3 ];then
tmp=$num1
num1=$num3
num3=$tmp
fi
# 如果 num2 大于 num3,就把 num2 和 num3 对标,确保 num2 变量中存的是小一点的值
if [ $num2 -gt $num3 ];then
tmp=$num2
num2=$num3
num3=$tmp
fi
echo "排序后数据(从小到大)为:$num1,$num2,$num3"
[root@neo ~]# bash bigest.sh
请输入一个整数:23
请输入一个整数:444
请输入一个整数:213
排序后数据(从小到大)为:23,213,444
[root@neo ~]# bash bigest.sh
请输入一个整数:aw
请输入一个整数,不能是其它字符!
[root@neo ~]# bash bigest.sh
请输入一个整数:
请输入一个整数,不能为空!
13、判断输入字符是否为数字(浮点数、偶数还是奇数)
#!/bin/bash
#
# 这个脚本用来判断后面的参数的种类(非数字,奇数,偶数,浮点数)
# 用法:Usag: [参数列表]
# 当参数个数小于1时,也就是没有整数输入,报错
if [ $# -lt 1 ] ; then
echo "Please INPUT at least ONE Number!"
exit 0
fi
# 将取出的参数传给程序bc,用它来检测这个参数是否为数字,并将错误信息重定向
for str in $* ; do
# echo "str is $str"
var=$(echo $str | bc 2> /dev/null)
# echo "var is $var"
# 如果传入的参数是一个数字,bc返回值就是这个数,否则不是,通过这个可以判断参数是否为数字
# 如果bc返回值与这个参数相同,则参数一定是数字,反之则不是
if [ "$var" != "$str" ] ; then
echo "$str isn't a number."
# 如果参数是数字,则只需要查找是否含有小数点来判断是否为浮点数
elif echo $str|grep "\." &> /dev/null ;then
echo "$str is a float numbe."
else
# 如果这个参数是一个整数,将他模2,余数为0则是偶数,为1则为奇数
if test `expr $str % 2` -eq 0 ; then
echo "$str is an even number."
else
echo "$str is an odd number."
fi
fi
done
exit
[root@Tang-Neo ~]# cat num1.sh
#!/bin/bash
#
if [ $# -lt 1 ] ; then
echo "Please INPUT at least ONE Number!"
exit 0
fi
for str in $* ; do
# echo "str is $str"
var=$(echo $str | bc 2> /dev/null)
# echo "var is $var"
if [ "$var" != "$str" ] ; then
echo "$str isn't a number."
elif echo $str | grep "\." &> /dev/null ;then
echo "$str is a float numbe."
else
if test `expr $str % 2` -eq 0 ; then
echo "$str is an even number."
else
echo "$str is an odd number."
fi
fi
done
exit
[root@Tang-Neo ~]# bash num1.sh 22 23 12 as 1.2 2.3
22 is an even number.
23 is an odd number.
12 is an even number.
as isn't a number.
1.2 is a float numbe.
2.3 is a float numbe.
13、判断输入字符是否为整数
[root@Tang-Neo ~]# cat num2.sh
#!/bin/bash
#
if [ $# -lt 1 ] ; then
echo "Please INPUT at least ONE Number!"
exit 0
fi
for var in $* ; do
if grep '^[[:digit:]]*$' <<< "$var" &> /dev/null; then
echo "$var is an integer."
else
echo "$var is not an integer."
fi
done
[root@Tang-Neo ~]# bash num2.sh a s 2 2.1 4
a is not an integer.
s is not an integer.
2 is an integer.
2.1 is not an integer.
4 is an integer.
[root@Tang-Neo ~]# bash num2.sh
Please INPUT at least ONE Number!
14、判断输入字符是否为整数(第二种方法)
[root@Tang-Neo ~]# cat num3.sh
#!/bin/bash
#
if [ $# -lt 1 ] ; then
echo "Please INPUT at least ONE Number!"
exit 0
fi
for str in $* ; do
if [ "$str" -gt 0 ] 2>/dev/null ;then
echo "$str is an integer."
else
echo "$str is not an integer."
fi
done
[root@Tang-Neo ~]# bash num3.sh 1 2 a c d 2.1 2
1 is an integer.
2 is an integer.
a is not an integer.
c is not an integer.
d is not an integer.
2.1 is not an integer.
2 is an integer.
15、判断输入字符是否为整数(第三种方法)
[root@neo ~]# cat num4.sh
#!/bin/bash
#
if [ $# -lt 1 ];then
echo "Please INPUT at least ONE Number!"
exit 1
fi
for str in $*; do
case "$str" in
[1-9]|[0-9]*)
if echo $str | grep "\." &> /dev/null ; then
echo "$str isn't an integer!"
exit 2
else
echo "$str is an integer."
fi
;;
*)
echo "$str isn't an integer!"
;;
esac
done
[root@neo ~]# bash num4.sh 2 5 a 3.2
2 is an integer.
5 is an integer.
a isn't an integer!
3.2 isn't an integer!
15、判断输入字符是否为整数(第四种方法)
[root@Tang-Neo ~]# cat num5.sh
#!/bin/bash
#
if [ $# -lt 1 ] ; then
echo "Please INPUT at least ONE Number!"
exit 0
fi
for str in $* ; do
expr $str "+" 10 &> /dev/null
if [ $? -eq 0 ];then
echo "$str is an integer."
else
echo "$str isn't an integer."
fi
done
[root@Tang-Neo ~]# bash num5.sh 2 1 as 2a 2.1
2 is an integer.
1 is an integer.
as isn't an integer.
2a isn't an integer.
2.1 isn't an integer.
16、剪刀石头布游戏(The Game of Scissors/Rock/Paper)
#!/bin/bash
# 编写脚本,实现人机<石头,剪刀,布>游戏
game=(石头 剪刀 布)
num=$[RANDOM%3]
computer=${game[$num]}
# 通过随机数获取计算机的出拳
# 出拳的可能性保存在一个数组中,game[0],game[1],game[2]分别是 3 中不同的可能
echo "请根据下列提示选择您的出拳手势"
echo "1.石头"
echo "2.剪刀"
echo "3.布"
read -p "请选择 1‐3:" person
case $person in
1)
if [ $num -eq 0 ]
then
echo "平局"
elif [ $num -eq 1 ]
then
echo "你赢"
else
echo "计算机赢"
fi;;
2)
if [ $num -eq 0 ]
then
echo "计算机赢"
elif [ $num -eq 1 ]
then
echo "平局"
else
echo "你赢"
fi;;
3)
if [ $num -eq 0 ]
then
echo "你赢"
elif [ $num -eq 1 ]
then
echo "计算机赢"
else
echo "平局"
fi;;
*)
echo "必须输入 1‐3 的数字"
esac
升级版:
[root@neo ~]# cat rockSCISSORSpaper.sh
#!/bin/bash
#
game=(Rock Scissors Paper)
num=$[RANDOM%3]
computer=${game[$num]}
echo "Please Choose one of the three:"
echo "1 Rock"
echo "2 Scissors"
echo "3 Paper"
read -p "Please choose one number of 1-3:" person
case $person in
1)
if [ $num -eq 0 ];then
echo "The Computer Choosed the ${computer}."
echo "You Choosed the Rock."
echo "You're Equal!"
elif [ $num -eq 1 ];then
echo "The Computer Choosed the ${computer}."
echo "You Choosed the Rock."
echo "You Win! "
else
echo "The Computer Choosed the ${computer}."
echo "You Choosed the Rock."
echo "The Computer Win!"
fi
;;
2)
if [ $num -eq 1 ];then
echo "The Computer Choosed the ${computer}."
echo "You Choosed the Scissors."
echo "You're Equal!"
elif [ $num -eq 2 ];then
echo "The Computer Choosed the ${computer}."
echo "You Choosed the Scissors."
echo "You Win! "
else
echo "The Computer Choosed the ${computer}."
echo "You Choosed the Scissors."
echo "The Computer Win!"
fi
;;
3)
if [ $num -eq 2 ];then
echo "The Computer Choosed the ${computer}."
echo "You Choosed the Paper."
echo "You're Equal!"
elif [ $num -eq 0 ];then
echo "The Computer Choosed the ${computer}."
echo "You Choosed the Paper."
echo "You Win! "
else
echo "The Computer Choosed the ${computer}."
echo "You Choosed the Paper."
echo "The Computer Win!"
fi
;;
*)
echo "Please INPUT 1 、 2 or 3!"
esac
[root@neo ~]# bash rockSCISSORSpaper.sh
Please Choose one of the three:
1 Rock
2 Scissors
3 Paper
Please choose one number of 1-3:
Please INPUT 1 、 2 or 3!
[root@neo ~]# bash rockSCISSORSpaper.sh
Please Choose one of the three:
1 Rock
2 Scissors
3 Paper
Please choose one number of 1-3:3
The Computer Choosed the Rock.
You Choosed the Papper.
You Win!
[root@neo ~]# bash rockSCISSORSpaper.sh
Please Choose one of the three:
1 Rock
2 Scissors
3 Paper
Please choose one number of 1-3:2
The Computer Choosed the Paper.
You Choosed the Scissors.
You Win!
[root@neo ~]# bash rockSCISSORSpaper.sh
Please Choose one of the three:
1 Rock
2 Scissors
3 Paper
Please choose one number of 1-3:2
The Computer Choosed the Scissors.
You Choosed the Scissors.
You're Equal!
17、编写脚本测试 192.168.4.0/24 整个网段中哪些主机处于开机状态,哪些主机处于关机状态(for 版本)
#!/bin/bash
# 编写脚本测试 192.168.4.0/24 整个网段中哪些主机处于开机状态,哪些主机处于关机
# 状态(for 版本)
for i in {1..254}
do
# 每隔0.3秒ping一次,一共ping2次,并以1毫秒为单位设置ping的超时时间
ping ‐c 2 ‐i 0.3 ‐W 1 192.168.4.$i &>/dev/null
if [ $? -eq 0 ];then
echo "192.168.4.$i is up"
else
echo "192.168.4.$i is down"
fi
done
18、编写脚本测试 192.168.4.0/24 整个网段中哪些主机处于开机状态,哪些主机处于关机状态(while 版本)
#!/bin/bash
# 编写脚本测试 192.168.4.0/24 整个网段中哪些主机处于开机状态,哪些主机处于关机
# 状态(while 版本)
i=1
while [ $i -le 254 ]
do
ping ‐c 2 ‐i 0.3 ‐W 1 192.168.4.$i &>/dev/null
if [ $? -eq 0 ];then
echo "192.168.4.$i is up"
else
echo "192.168.4.$i is down"
fi
let i++
done
19、编写脚本测试 192.168.4.0/24 整个网段中哪些主机处于开机状态,哪些主机处于关机状态(多进程版)
#!/bin/bash
# 编写脚本测试 192.168.4.0/24 整个网段中哪些主机处于开机状态,哪些主机处于关机
# 状态(多进程版)
#定义一个函数,ping 某一台主机,并检测主机的存活状态
myping(){
ping ‐c 2 ‐i 0.3 ‐W 1 $1 &>/dev/null
if [ $? -eq 0 ];then
echo "$1 is up"
else
echo "$1 is down"
fi
}
for i in {1..254}
do
myping 192.168.4.$i &
done
# 使用&符号,将执行的函数放入后台执行
# 这样做的好处是不需要等待ping第一台主机的回应,就可以继续并发ping第二台主机,依次类推。
20、打印九九乘法表
#!/bin/bash
# 9*9 乘法表(编写 shell 脚本,打印 9*9 乘法表)
for i in `seq 9`
do
for j in `seq $i` ;do
echo -n "$j*$i=$[i*j] "
done
echo
done
21、使用死循环实时显示 enp1s0 网卡发送的数据包流量
#!/bin/bash
# 使用死循环实时显示 enp1s0 网卡发送的数据包流量
while :
do
echo '本地网卡 enp1s0 流量信息如下: '
ifconfig enp1s0 | grep "RX pack" | awk '{print $5}'
ifconfig enp1s0 | grep "TX pack" | awk '{print $5}'
sleep 1
done
22、使用 user.txt 文件中的人员名单,在计算机中自动创建对应的账户并配置初始密码本脚本执行,需要提前准备一个 user.txt 文件,该文件中包含有若干用户名信息
#!/bin/bash
# 使用 user.txt 文件中的人员名单,在计算机中自动创建对应的账户并配置初始密码
# 本脚本执行,需要提前准备一个 user.txt 文件,该文件中包含有若干用户名信息
for i in `cat user.txt`
do
useradd $i
echo "123456" | passwd ‐‐stdin $i
done
23、编写批量修改扩展名脚本
[root@neo test]# cat nameCHANGE.sh
#!/bin/bash
#
for i in `ls *.$1`;do
newNAME=$(echo $i | cut -d "." -f 1)
echo "$i ---> ${newNAME}.$2"
mv $i ${newNAME}.$2
done
[root@neo test]# ls
nameCHANGE.sh
[root@neo test]# touch {1..5}.txt
[root@neo test]# ls
1.txt 2.txt 3.txt 4.txt 5.txt nameCHANGE.sh
[root@neo test]# bash nameCHANGE.sh txt jpg
1.txt ---> 1.jpg
2.txt ---> 2.jpg
3.txt ---> 3.jpg
4.txt ---> 4.jpg
5.txt ---> 5.jpg
[root@neo test]# ls
1.jpg 2.jpg 3.jpg 4.jpg 5.jpg nameCHANGE.sh
24、使用 expect 工具自动交互密码远程其他主机安装 httpd 软件
#!/bin/bash
# 使用 expect 工具自动交互密码远程其他主机安装 httpd 软件
# 删除~/.ssh/known_hosts 后,ssh 远程任何主机都会询问是否确认要连接该主机
rm ‐rf ~/.ssh/known_hosts
expect <<EOF
spawn ssh 192.168.4.254
expect "yes/no" {send "yes\r"}
# 根据自己的实际情况将密码修改为真实的密码字串
expect "password" {send "密码\r"}
expect "#" {send "yum ‐y install httpd\r"}
expect "#" {send "exit\r"}
EOF
25、一键部署 LNMP(源码安装版本)
#!/bin/bash
# 一键部署 LNMP(源码安装版本)
menu()
{
clear
echo " ##############‐‐‐‐Menu‐‐‐‐##############"
echo "# 1. Install Nginx"
echo "# 2. Install MySQL"
echo "# 3. Install PHP"
echo "# 4. Exit Program"
echo " ########################################"
}
choice()
{
read -p "Please choice a menu[1‐9]:" select
}
install_nginx()
{
id nginx &>/dev/null
if [ $? -ne 0 ];then
useradd -s /sbin/nologin nginx
fi
if [ -f nginx‐1.8.0.tar.gz ];then
tar -xf nginx‐1.8.0.tar.gz
cd nginx‐1.8.0
yum -y install gcc pcre‐devel openssl‐devel zlib‐devel make
./configure ‐‐prefix=/usr/local/nginx ‐‐with‐http_ssl_module
make
make install
ln -s /usr/local/nginx/sbin/nginx /usr/sbin/
cd ..
else
echo "没有 Nginx 源码包"
fi
}
install_mysql()
{
yum -y install gcc gcc‐c++ cmake ncurses‐devel perl
id mysql &>/dev/null
if [ $? -ne 0 ];then
useradd -s /sbin/nologin mysql
fi
if [ -f mysql‐5.6.25.tar.gz ];then
tar -xf mysql‐5.6.25.tar.gz
cd mysql‐5.6.25
cmake .
make
make install
/usr/local/mysql/scripts/mysql_install_db ‐‐user=mysql ‐‐datadir=/usr/local/mysql/data/
‐‐basedir=/usr/local/mysql/
chown -R root.mysql /usr/local/mysql
chown -R mysql /usr/local/mysql/data
/bin/cp -f /usr/local/mysql/support‐files/mysql.server /etc/init.d/mysqld
chmod +x /etc/init.d/mysqld
/bin/cp -f /usr/local/mysql/support‐files/my‐default.cnf /etc/my.cnf
echo "/usr/local/mysql/lib/" >> /etc/ld.so.conf
ldconfig
echo 'PATH=\$PATH:/usr/local/mysql/bin/' >> /etc/profile
export PATH
else
echo "没有 mysql 源码包"
exit
fi
}
install_php()
{
#安装 php 时没有指定启动哪些模块功能,如果的用户可以根据实际情况自行添加额外功能如‐‐with‐gd 等
yum -y install gcc libxml2‐devel
if [ -f mhash‐0.9.9.9.tar.gz ];then
tar -xf mhash‐0.9.9.9.tar.gz
cd mhash‐0.9.9.9
./configure
make
make install
cd ..
if [ ! ‐f /usr/lib/libmhash.so ];then
ln -s /usr/local/lib/libmhash.so /usr/lib/
fi
ldconfig
else
echo "没有 mhash 源码包文件"
exit
fi
if [ -f libmcrypt‐2.5.8.tar.gz ];then
tar -xf libmcrypt‐2.5.8.tar.gz
cd libmcrypt‐2.5.8
./configure
make
make install
cd ..
if [ ! -f /usr/lib/libmcrypt.so ];then
ln -s /usr/local/lib/libmcrypt.so /usr/lib/
fi
ldconfig
else
echo "没有 libmcrypt 源码包文件"
exit
fi
if [ -f php‐5.4.24.tar.gz ];then
tar -xf php‐5.4.24.tar.gz
cd php‐5.4.24
./configure ‐‐prefix=/usr/local/php5 ‐‐with‐mysql=/usr/local/mysql ‐‐enable‐fpm ‐‐
enable‐mbstring ‐‐with‐mcrypt ‐‐with‐mhash ‐‐with‐config‐file‐path=/usr/local/php5/etc ‐‐with‐
mysqli=/usr/local/mysql/bin/mysql_config
make && make install
/bin/cp -f php.ini‐production /usr/local/php5/etc/php.ini
/bin/cp -f /usr/local/php5/etc/php‐fpm.conf.default /usr/local/php5/etc/php‐fpm.conf
cd ..
else
echo "没有 php 源码包文件"
exit
fi
}
while :
do
menu
choice
case $select in
1)
install_nginx
;;
2)
install_mysql
;;
3)
install_php
;;
4)
exit
;;
*)
echo Sorry!
esac
done
26、100以内的正整数之和
[root@neo test]# cat sum100.sh
#!/bin/bash
#
declare -i sum=0
for i in {1..100};do
let sum+=$i
done
echo "The sum of integer between 1 and 100 is: $sum."
[root@neo test]# bash sum100.sh
The sum of integer between 1 and 100 is: 5050.
27、任意正整数内的正整数之和
[root@neo test]# cat sumANYinteger.sh
#!/bin/bash
#
read -p "Please INPUT any integer:" integer
declare -i sum=0
for i in `seq $integer`;do
let sum+=$i
done
echo "The sum of integer between 1 and $integer is: $sum."
[root@neo test]# bash sumANYinteger.sh
Please INPUT any integer:99
The sum of integer between 1 and 99 is: 4950.
[root@neo test]# bash sumANYinteger.sh
Please INPUT any integer:100
The sum of integer between 1 and 100 is: 5050.
[root@neo test]# bash sumANYinteger.sh
Please INPUT any integer:11111
The sum of integer between 1 and 11111 is: 61732716.
28、统计 13:30 到 14:30 所有访问 apache 服务器的请求有多少个
#!/bin/bash
# 统计 13:30 到 14:30 所有访问 apache 服务器的请求有多少个
# awk 使用‐F 选项指定文件内容的分隔符是/或者:
# 条件判断$7:$8 大于等于 13:30,并且要求,$7:$8 小于等于 14:30
# 最后使用 wc ‐l 统计这样的数据有多少行,即多少个
awk -F "[ /:]" '$7":"$8>="13:30" && $7":"$8<="14:30"' /var/log/httpd/access_log |wc -l
29、统计 13:30 到 14:30 所有访问本机 Aapche 服务器的远程 IP 地址是什么
#!/bin/bash
# 统计 13:30 到 14:30 所有访问本机 Aapche 服务器的远程 IP 地址是什么
# awk 使用‐F 选项指定文件内容的分隔符是/或者:
# 条件判断$7:$8 大于等于 13:30,并且要求,$7:$8 小于等于 14:30
# 日志文档内容里面,第 1 列是远程主机的 IP 地址,使用 awk 单独显示第 1 列即可
awk -F "[ /:]" '$7":"$8>="13:30" && $7":"$8<="14:30"{print $1}' /var/log/httpd/access_log
30、统计每个远程 IP 访问了本机 apache 几次
#!/bin/bash
# 统计每个远程 IP 访问了本机 apache 几次?
awk '{ip[$1]++}END{for(i in ip){print ip[i],i}}' /var/log/httpd/access_log
31、统计当前 Linux 系统中可以登录计算机的账户有多少个
#!/bin/bash
# 统计当前 Linux 系统中可以登录计算机的账户有多少个
#方法 1:
grep "bash$" /etc/passwd | wc -l
#方法 2:
awk -f: '/bash$/{x++}end{print x}' /etc/passwd
32、统计/var/log 有多少个文件,并显示这些文件名
#!/bin/bash
# 统计/var/log 有多少个文件,并显示这些文件名
# 使用 ls 递归显示所有,再判断是否为文件,如果是文件则计数器加 1
cd /var/log
sum=0
for i in `ls -r *`
do
if [ -f $i ];then
let sum++
echo "文件名:$i"
fi
done
echo "总文件数量为:$sum"
33、判断/var/log目录下的每一个文件的内容类型,并统计普通文件的数量
[root@neo test]# cat fileTYPE.sh
#!/bin/bash
#
declare -i commonfilesum=0
for filename in /var/log/*; do
if [ -f $filename ]; then
echo "$filename is Common file."
commonfilesum=$[$commonfilesum+1]
elif [ -d $filename ]; then
echo "$filename is Directory."
elif [ -L $filename ]; then
echo "$filename is Symbolic link."
elif [ -b $filename ]; then
echo "$filename is block special file."
elif [ -c $filename ]; then
echo "$filename is character special file."
elif [ -S $filename ]; then
echo "$filename is Socket file."
else
echo "$filename is Unkown."
fi
done
echo "The num of common file is $commonfilesum."
[root@neo test]# bash fileTYPE.sh
/var/log/anaconda is Directory.
/var/log/audit is Directory.
/var/log/boot.log is Common file.
/var/log/boot.log-20190808 is Common file.
/var/log/boot.log-20190817 is Common file.
/var/log/btmp is Common file.
/var/log/chrony is Directory.
/var/log/cron is Common file.
/var/log/cron-20190811 is Common file.
/var/log/cron-20190818 is Common file.
/var/log/dmesg is Common file.
/var/log/dmesg.old is Common file.
/var/log/firewalld is Common file.
/var/log/grubby_prune_debug is Common file.
/var/log/httpd is Directory.
/var/log/lastlog is Common file.
/var/log/maillog is Common file.
/var/log/maillog-20190811 is Common file.
/var/log/maillog-20190818 is Common file.
/var/log/mariadb is Directory.
/var/log/messages is Common file.
/var/log/messages-20190811 is Common file.
/var/log/messages-20190818 is Common file.
/var/log/rhsm is Directory.
/var/log/secure is Common file.
/var/log/secure-20190811 is Common file.
/var/log/secure-20190818 is Common file.
/var/log/spooler is Common file.
/var/log/spooler-20190811 is Common file.
/var/log/spooler-20190818 is Common file.
/var/log/tallylog is Common file.
/var/log/tuned is Directory.
/var/log/wpa_supplicant.log is Common file.
/var/log/wpa_supplicant.log-20190809 is Common file.
/var/log/wpa_supplicant.log-20190819 is Common file.
/var/log/wtmp is Common file.
/var/log/xferlog is Common file.
/var/log/xferlog-20190818 is Common file.
/var/log/yum.log is Common file.
The num of common file is 32.
34、将文件中所有的小写字母转换为大写字母
#!/bin/bash
# 将文件中所有的小写字母转换为大写字母
# $1是位置参数,是你需要转换大小写字母的文件名称
# 执行脚本,给定一个文件名作为参数,脚本就会将该文件中所有的小写字母转换为大写字母
tr "[a‐z]" "[A‐Z]" < $1
35、检查特定的软件包是否已经安装
#!/bin/bash
# 检查特定的软件包是否已经安装
if [ $# -eq 0 ];then
echo "你需要制定一个软件包名称作为脚本参数"
echo "用法:$0 软件包名称 ..."
fi
# $@提取所有的位置变量的值,相当于$*
for package in "$@"
do
if rpm -q ${package} &>/dev/null ;then
echo -e "${package}\033[32m 已经安装\033[0m"
else
echo -e "${package}\033[34;1m 未安装\033[0m"
fi
done
[root@neo ~]# bash yesORnoINSTALL.sh ssh
ssh 未安装
[root@neo ~]# bash yesORnoINSTALL.sh telnet
telnet 已经安装
[root@neo ~]# bash yesORnoINSTALL.sh httpd
httpd 已经安装
36、监控 HTTP 服务器的状态(测试返回码)
#!/bin/bash
# 监控 HTTP 服务器的状态(测试返回码)
# 设置变量,url为你需要检测的目标网站的网址(IP 或域名),比如百度
url=http://http://183.232.231.172/index.html
# 定义函数 check_http:
# 使用 curl 命令检查 http 服务器的状态
# ‐m 设置curl不管访问成功或失败,最大消耗的时间为 5 秒,5 秒连接服务为相应则视为无法连接
# ‐s 设置静默连接,不显示连接时的连接速度、时间消耗等信息
# ‐o 将 curl 下载的页面内容导出到/dev/null(默认会在屏幕显示页面内容)
# ‐w 设置curl命令需要显示的内容%{http_code},指定curl返回服务器的状态码
check_http()
{
status_code=$(curl -m 5 -s -o /dev/null -w %{http_code} $url)
}
while :
do
check_http
date=$(date +%Y%m%d‐%H:%M:%S)
# 生成报警邮件的内容
echo "当前时间为:$date
$url 服务器异常,状态码为${status_code}.
请尽快排查异常." > /tmp/http$$.pid
# 指定测试服务器状态的函数,并根据返回码决定是发送邮件报警还是将正常信息写入日志
if [ $status_code -ne 200 ];then
mail -s Warning root < /tmp/http$$.pid
else
echo "$url 连接正常" >> /var/log/http.log
fi
sleep 5
done
37、自动添加防火墙规则,开启某些服务或端口(适用于 RHEL7)
#!/bin/bash
# 自动添加防火墙规则,开启某些服务或端口(适用于 RHEL7)
#
# 设置变量定义需要添加到防火墙规则的服务和端口号
# 使用 firewall‐cmd ‐‐get‐services 可以查看 firewall 支持哪些服务
service="nfs http ssh"
port="80 22 8080"
# 循环将每个服务添加到防火墙规则中
for i in $service
do
echo "Adding $i service to firewall"
firewall‐cmd --add-service=${i}
done
#循环将每个端口添加到防火墙规则中
for i in $port
do
echo "Adding $i Port to firewall"
firewall‐cmd --add-port=${i}/tcp
done
#将以上设置的临时防火墙规则,转换为永久有效的规则(确保重启后有效)
firewall‐cmd --runtime-to-permanent
38、使用脚本自动创建逻辑卷
#!/bin/bash
# 使用脚本自动创建逻辑卷
# 清屏,显示警告信息,创建将磁盘转换为逻辑卷会删除数据
clear
echo -e "\033[32m !!!!!!警告(Warning)!!!!!!\033[0m"
echo
echo "+++++++++++++++++++++++++++++++++++++++++++++++++"
echo "脚本会将整个磁盘转换为 PV,并删除磁盘上所有数据!!!"
echo "This Script will destroy all data on the Disk"
echo "+++++++++++++++++++++++++++++++++++++++++++++++++"
echo
read -p "请问是否继续 y/n?:" sure
# 测试用户输入的是否为 y,如果不是则退出脚本
[ $sure != y ] && exit
# 提示用户输入相关参数(磁盘、卷组名称等数据),并测试用户是否输入了这些值,如果没有输入,则脚本退出
read -p "请输入磁盘名称,如/dev/vdb:" disk
[ -z $disk ] && echo "没有输入磁盘名称" && exit
read -p "请输入卷组名称:" vg_name
[ -z $vg_name ] && echo "没有输入卷组名称" && exit
read -p "请输入逻辑卷名称:" lv_name
[ -z $lv_name ] && echo "没有输入逻辑卷名称" && exit
read -p "请输入逻辑卷大小:" lv_size
[ -z $lv_size ] && echo "没有输入逻辑卷大小" && exit
# 使用命令创建逻辑卷
pvcreate $disk
vgcreate $vg_name $disk
lvcreate -L ${lv_size}M -n ${lv_name} ${vg_name}
39、显示 CPU 厂商信息
#!/bin/bash
# 显示 CPU 厂商信息
awk '/vendor_id/{print $3}' /proc/cpuinfo | uniq
40、删除某个目录下大小为 0 的文件
#!/bin/bash
# 删除某个目录下大小为 0 的文件
#/var/www/html 为测试目录,脚本会清空该目录下所有 0 字节的文件
dir="/var/www/html"
find $dir -type f -size 0 -exec rm -rf {} \;
41、查找 Linux 系统中的僵尸进程
#!/bin/bash
# 查找 Linux 系统中的僵尸进程
# awk 判断 ps 命令输出的第 8 列为 Z 是,显示该进程的 PID 和进程命令
ps aux | awk '{if($8 == "Z"){print $2,$11}}'
42、提示用户输入年份后判断该年是否为闰年
#!/bin/bash
# 提示用户输入年份后判断该年是否为闰年
# 能被4整除并且并不能被100整除的年份是闰年
# 能被400整除的年份也是闰年
read -p "请输入一个年份:" year
if [ "$year" = "" ];then
echo "没有输入年份"
exit
fi
#使用正则测试变量 year 中是否包含大小写字母
if [[ "$year" =~ [a‐Z] ]];then
echo "你输入的不是数字"
exit
fi
# 判断是否为闰年
if [ $[year % 4] -eq 0 ] && [ $[year % 100] -ne 0 ];then
echo "$year年是闰年"
elif [ $[year % 400] -eq 0 ];then
echo "$year年是闰年"
else
echo "$year年不是闰年"
fi
[root@neo ~]# cat leapYEAR.sh
#!/bin/bash
#
read -p "Please INPUT A Year,Such As 2000:" year
if [ "$year" == "" ];then
echo "You Input Nothing!"
exit 0
fi
if [[ "$year" =~ [a-Z] ]];then
echo "You Input The Wrong Argument!"
exit 0
fi
if [ $(($year%4)) -eq 0 ] && [ $(($year%100)) -ne 0 ];then
echo "The Year $year IS A LEAP YEAR!"
elif [ $(($year%400)) -eq 0 ];then
echo "The Year $year IS A LEAP YEAR!"
else
echo "The Year $year IS NOT A LEAP YEAR!"
fi
[root@neo ~]# bash leapYEAR.sh
Please INPUT A Year,Such As 2000:1997
The Year 1997 IS NOT A LEAP YEAR!
[root@neo ~]# bash leapYEAR.sh
Please INPUT A Year,Such As 2000:2000
The Year 2000 IS A LEAP YEAR!
[root@neo ~]# bash leapYEAR.sh
Please INPUT A Year,Such As 2000:2100
The Year 2100 IS NOT A LEAP YEAR!
43、生成随机密码(urandom 版本)
#!/bin/bash
# 生成随机密码(urandom 版本)
# /dev/urandom 文件是 Linux 内置的随机设备文件
# cat /dev/urandom 可以看看里面的内容,ctrl+c 退出查看
# 查看该文件内容后,发现内容有些太随机,包括很多特殊符号,我们需要的密码不希望使用这些符号
# tr ‐dc '_A‐Za‐z0‐9' < /dev/urandom
# 该命令可以将随机文件中其他的字符删除,仅保留大小写字母,数字,下划线,但是内容还是太多
# 我们可以继续将优化好的内容通过管道传递给 head 命令,在大量数据中仅显示头 10 个字节
# 注意 A 前面有个下划线
tr -dc '_A‐Za‐z0‐9' </dev/urandom | head -c 10
44、生成随机密码(字串截取版本)
#!/bin/bash
# 生成随机密码(字串截取版本)
# 设置变量 key,存储密码的所有可能性(密码库),如果还需要其他字符请自行添加其他密码字符
# 使用$#统计密码库的长度
key="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
num=${#key}
# 设置初始密码为空
pass=''
# 循环 8 次,生成随机密码
# 每次都是随机数对密码库的长度取余,确保提取的密码字符不超过密码库的长度
# 每次循环提取一位随机密码,并将该随机密码追加到 pass 变量的最后
for i in {1..8}
do
index=$[RANDOM%num]
pass=$pass${key:$index:1}
done
echo $pass
45、生成随机密码(UUID 版本,16 进制密码)
#!/bin/bash
# 生成随机密码(UUID 版本,16 进制密码)
uuidgen
46、生成随机密码(进程 ID 版本,数字密码)
#!/bin/bash
# 生成随机密码(进程 ID 版本,数字密码)
echo $$
47、生成随机密码(使用openssl rand工具)
[root@neo ~]# cat generatedRANDOM.sh
#!/bin/bash
#
openssl rand -hex 4
[root@neo ~]# bash generatedRANDOM.sh
d9a12c8f
[root@neo ~]# bash generatedRANDOM.sh
bafc1efc
48、测试用户名与密码是否正确
#!/bin/bash
# 循环测试用户名与密码是否正确
# 循环测试用户的账户名和密码,最大测试 3 次,输入正确提示登录成功,否则提示登录失败
# 用户名为 tom 并且密码为 123456
for i in {1..3}
do
read -p "请输入用户名:" user
read -p "请输入密码:" pass
if [ "$user" == 'tom' -a "$pass" == '123456' ];then
echo "Login successful"
exit
fi
done
echo "Login Failed"
49、Shell 脚本的 fork 炸弹
#!/bin/bash
# Shell 脚本的 fork 炸弹
# 快速消耗计算机资源,致使计算机死机
# 定义函数名为.(点), 函数中递归调用自己并放入后台执行
.() { .|.& };.
50、批量下载有序文件(pdf、图片、视频等等)
#!/bin/bash
# 批量下载有序文件(pdf、图片、视频等等)
# 本脚本准备有序的网络资料进行批量下载操作(如 01.jpg,02.jpg,03.jpg)
# 设置资源来源的域名连接
url="http://www.baidu.com/"
echo "开始下载..."
sleep 2
type=jpg
for i in `seq 100`
echo "正在下载$i.$type"
curl $url/$i.$type -o /tmp/${i}$type
sleep 1
done
#curl 使用-o 选项指定下载文件另存到哪里.
51、显示当前计算机中所有账户的用户名称
#!/bin/bash
# 显示当前计算机中所有账户的用户名称
# 下面使用3种不同的方式列出计算机中所有账户的用户名
# 指定以:为分隔符,打印/etc/passwd 文件的第 1 列
awk -F: '{print $1}' /etc/passwd
# 指定以:为分隔符,打印/etc/passwd 文件的第 1 列
cut -d: -f1 /etc/passwd
# 使用 sed 的替换功能,将/etc/passwd 文件中:后面的所有内容替换为空(仅显示用户名)
sed 's/:.*//' /etc/passwd
52、打包备份某目录,指定目录路径,脚本自动将该目录使用 tar 命令打包备份到 /data 目录
#!/bin/bash
# 制定目录路径,脚本自动将该目录使用 tar 命令打包备份到/data目录
[ ! -d /data ] && mkdir /data
[ -z $1 ] && exit
if [ -d $1 ];then
tar -czf /data/$1.-`date +%Y%m%d`.tar.gz $1
else
echo "该目录不存在"
fi
53、编写一个脚本,找出172.16.141.X网络中哪些主机地址被使用,哪些未被使用,并把结果保存至相应的文件中
[root@LEEMUMU ~]# cat ping.sh
#!/bin/bash
#
declare -i upnum=0
declare -i downnum=0
declare -i i=1
pinghost() {
if ping $1 -c 1 -W 1 &>/dev/null; then
echo -e "\033[1;32m$1 is up.\033[0m" | tee -a up20190717.txt
upnum=$[$upnum+1]
else
echo -e "\033[1;31m$1 is down.\033[0m" | tee -a down20190717.txt
downnum=$[$downnum+1]
fi
}
while [ $i -le 254 ]; do
pinghost 172.16.141.$i
let i++
done
echo "Uphost is $upnum."
echo "Downhost is $downnum."
54、编写脚本,通过命令行参数传入一个用户名,判断ID是偶数还是奇数
[root@LeeMumu ~]# cat evenorodd.sh
#!/bin/bash
#
read -p "Please Input One UserName:" UserName
if ! id $UserName &> /dev/null; then
echo -e "\e[1;31mThe $UserName Not Exist!\e[0m"
echo -e "\e[1;32mPlease Input Another UserName!\e[0m"
exit 1
else
if [ $[`id -u $UserName`%2] -eq 0 ];then
echo -e "\e[1;33mThe UserID Of $UserName is even!\e[0m"
else
echo -e "\e[1;34mThe UserID Of $UserName is odd!\e[0m"
fi
fi
[root@LeeMumu ~]# ./evenorodd.sh
Please Input One UserName:JC9
The UserID Of JC9 is even!
[root@LeeMumu ~]# ./evenorodd.sh
Please Input One UserName:jc8
The jc8 Not Exist!
Please Input Another UserName!
[root@LeeMumu ~]# ./evenorodd.sh
Please Input One UserName:JC6
The UserID Of JC6 is odd!
55、安装 LAMP 环境(yum 版本)
#!/bin/bash
# 安装 LAMP 环境(yum 版本)
# 本脚本适用于 RHEL7(RHEL6 中数据库为 mysql)
yum makecache &>/dev/null
num=$(yum repolist | awk '/repolist/{print $2}' | sed 's/,//')
if [ $num -lt 0 ];then
yum -y install httpd
yum -y install mariadb mariadb-server mariadb-devel
yum -y install php php-mysql
else
echo "未配置 yum 源..."
fi
56、循环关闭局域网中所有主机
#!/bin/bash
# 循环关闭局域网中所有主机
# 假设本机为 192.168.4.100,编写脚本关闭除自己外的其他所有主机
# 脚本执行,需要提前给所有其他主机传递 ssh 密钥,满足无密码连接
for i in {1..254}
do
[ $i -eq 100 ] && continue
echo "正在关闭 192.168.4.$i..."
ssh 192.168.4.$i poweroff
done
57、计算当前系统上的所有用的id之和
[root@neo ~]# cat uidSUM.sh
#!/bin/bash
#
declare -i passwd_Lines=`wc -l /etc/passwd | cut -d' ' -f1`
declare -i sum_UID=0
for i in `cat /etc/passwd | cut -d':' -f3`; do
sum_UID=$[$sum_UID+$i]
done
echo "There are $passwd_Lines users."
echo "The sum of the user-ID is:$sum_UID"
[root@neo ~]# bash uidSUM.sh
There are 34 users.
The sum of the user-ID is:75452
58、非交互自动生成 SSH 密钥文件
#!/bin/bash
# 非交互自动生成 SSH 密钥文件
# ‐t 指定 SSH 密钥的算法为 RSA 算法;‐N 设置密钥的密码为空;‐f 指定生成的密钥文件>存放在哪里
rm -rf ~/.ssh/{known_hosts,id_rsa*}
ssh‐keygen -t RSA -N '' -f ~/.ssh/id_rsa
59、检查特定的软件包是否已经安装
#!/bin/bash
# 检查特定的软件包是否已经安装
if [ $# -eq 0 ];then
echo "你需要制定一个软件包名称作为脚本参数"
echo "用法:$0 软件包名称 ..."
fi
# $@提取所有的位置变量的值,相当于$*
for package in "$@"
do
if rpm -q ${package} &>/dev/null ;then
echo -e "${package}\033[32m 已经安装\033[0m"
else
echo -e "${package}\033[34;1m 未安装\033[0m"
fi
done
[root@Tang ~]# cat packageYesOrNo.sh
#!/bin/bash
#
if [ $# -eq 0 ];then
echo -e "\033[31mNo Arguements! Please INPUT SOME ARGUMENTS!\033[0m"
echo -e "\033[32mSyntax: bash packageYesOrNo.sh PackageName1 PackageName2 PackageName3 ...\033[0m"
echo -e "\033[32mSyntax: ./packageYesOrNo.sh PackageName1 PackageName2 PackageName3 ...\033[0m"
echo -e "\033[32mSyntax: source packageYesOrNo.sh PackageName1 PackageName2 PackageName3 ...\033[0m"
fi
for package in "$@"
do
if rpm -q ${package} &>/dev/null ;then
echo -e "${package}\033[32m Installed!\033[0m"
else
echo -e "${package}\033[31;1m Not Installed!\033[0m"
fi
done
[root@Tang ~]# source packageYesOrNo.sh
No Arguements! Please INPUT SOME ARGUMENTS!
Syntax: bash packageYesOrNo.sh PackageName1 PackageName2 PackageName3 ...
Syntax: ./packageYesOrNo.sh PackageName1 PackageName2 PackageName3 ...
Syntax: source packageYesOrNo.sh PackageName1 PackageName2 PackageName3 ...
[root@Tang ~]# source packageYesOrNo.sh epel-release vim nginx
epel-release Installed!
vim Not Installed!
nginx Installed!
60、指定目录,进行压缩,并保存至 /data 目录下
[root@luna-sybil test]# cat tar-directory.sh
#!/bin/bash
[ ! -d /data ] && mkdir /data
[ -z $1 ] && exit
if [ -d $1 ]; then
tar -czf /data/$1.-`date +%Y%m%d`.tar.gz $1
else
echo "The Directory doesn't exist."
fi
[root@luna-sybil test]# tree ../test/
../test/
├── tar-directory.sh
├── test1
│ ├── test1-1
│ ├── test1-2
│ ├── test1-3
│ ├── test1-4
│ └── test1-5
├── test2
│ ├── test2-1
│ ├── test2-2
│ ├── test2-3
│ ├── test2-4
│ └── test2-5
└── test3
├── test3-1
├── test3-2
├── test3-3
├── test3-4
└── test3-5
3 directories, 16 files
[root@luna-sybil test]# bash tar-directory.sh test1
[root@luna-sybil test]# bash tar-directory.sh test2
[root@luna-sybil test]# bash tar-directory.sh test3
[root@luna-sybil test]# ll /data/
total 12
-rw-r--r-- 1 root root 178 Jul 8 11:25 test1.-20200708.tar.gz
-rw-r--r-- 1 root root 178 Jul 8 11:26 test2.-20200708.tar.gz
-rw-r--r-- 1 root root 178 Jul 8 11:26 test3.-20200708.tar.gz
61、显示主机上现在所有的监听端口
[root@luna-sybil test]# cat port-list.sh
#!/bin/bash
ss -nutlp | awk '{print $1,$5}' | awk -F"[: ]" '{print "Protocol:"$1,"Port:"$NF}'
[root@luna-sybil test]# bash port-list.sh
Protocol:Netid Port:Local
Protocol:udp Port:323
Protocol:udp Port:323
Protocol:tcp Port:22
Protocol:tcp Port:25
Protocol:tcp Port:22
Protocol:tcp Port:25
[root@luna-sybil test]# ss -nutlp
Netid State Recv-Q Send-Q Local Address:Port Peer Address:Port
udp UNCONN 0 0 127.0.0.1:323 *:* users:(("chronyd",pid=6461,fd=5))
udp UNCONN 0 0 ::1:323 :::* users:(("chronyd",pid=6461,fd=6))
tcp LISTEN 0 128 *:22 *:* users:(("sshd",pid=6797,fd=3))
tcp LISTEN 0 100 127.0.0.1:25 *:* users:(("master",pid=6998,fd=13))
tcp LISTEN 0 128 :::22 :::* users:(("sshd",pid=6797,fd=4))
tcp LISTEN 0 100 ::1:25 :::* users:(("master",pid=6998,fd=14))
62、返回计算机当前时间,并返回问候语,可以设置为开机启动
[root@luna-sybil test]# cat hello.sh
#!/bin/bash
tm=$(date +%H)
if [ $tm -le 12 ];then
msg="Good Morning $USER"
elif [ $tm -gt 12 -a $tm -le 18 ];then
msg="Good Afternoon $USER"
else
msg="Good Night $USER"
fi
echo "当前时间是:$(date +"%Y‐%m‐%d %H:%M:%S")"
echo -e "\033[34m$msg\033[0m"
[root@luna-sybil test]# bash hello.sh
当前时间是:2020‐07‐08 15:04:24
Good Afternoon root
[root@luna-sybil test]# bash hello.sh
当前时间是:2020‐07‐08 15:04:26
Good Afternoon root