#! /bin/bash
#猜年龄 版本1
age=87
read -p 'num: ' n
if [ $n -eq $age ]; then
echo 'you get it'
elif [ $n -gt $age ]; then
echo 'too big'
elif [ $n -lt $age]; then
ehco 'too small'
fi
#猜年龄 版本2
read -p ">>>" num
[[ ! $num =~ ^[0-9]+$ ]] && echo "enter numbers" && exit
if [ $num -gt 18];then
echo "too big"
elif [ $num -lt 18];then
echo "too small"
else
echo "you got it"
fi
#查成绩 版本1
read -p "enter your score:" score
if [ $score -ge 90 ]; then
echo "A"
elif [ $score -ge 80 -a $score -lt 90 ]; then
echo "A-"
elif [ $score -ge 70 -a $score -lt 80 ]; then
echo "B+"
elif [ $score -lt 70 ]; then
echo "B"
fi
#查成绩 版本2
read -p "enter your score" score
[[ ! $score =~ ^[0-9]+$ ]] && echo "please enter number" && exit
if [ $score -ge 90 ];then
echo "A"
elif [ $score -ge 80 ];then
echo "B"
elif [ $echo -ge 70 ];then
echo "C"
else
echo "d"
fi
#判断是否是数字
read -p "please enter a number:" num
while:
do
if [[ $num =~ ^[0-9]+$ ]];then
break
else
read -p "not a number, pleas enter a number:" num
fi
done
echo "the number you enter is $num"
#编写一个脚本,命令行传入一个文件路径,判断文件的类型
if [ -d $1 ]; then #相当于用test测试运算符 “test -d /目录” 命令
echo "$1 is directory"
elif [ -b $1 ];then
echo "$1 is block"
elif [ -f $1 ];then
echo "$1 is regular file"
else
echo "unknown"
fi
#检测制定的主机是否可以ping通,必须使用$1变量
ping -c2 $1 &> /dev/null
if [ $? -eq 0 ];then
echo "ok"
else
echo "down"
fi
#判断一个用户是否存在
id $1 &> /dev/null
if [ $? -eq 0 ];then
echo "user $1 exists"
else
echo "user $1 not exists"
fi
#检测httpd
rpm -q httpd &>/dev/null
if [ $? -eq 0 ];then
echo "already installed"
else
echo "intalling now..."
yum install httpd -y &>/dev/null
fi
#判断80端口的状态,未开启则重启
netstat -an | grep LISTEN | grep '\b80\b' &>/dev/null
if [ $? -eq 0 ];then
echo "port 80 is ok"
else
echo "port 80 is down"
echo "restart now..."
systemctl restart httpd &> /dev/null
if [ $? -eq 0 ];then
echo "restart successful"
else
echo "restart failed"
fi
fi
#编写监控脚本,如果根分区剩余空间小于10%,内存可用空间小月30%,就向管理员发送警告邮件,邮件内容包含相关信息
#提取根分区剩余空间:
use_disk = `df /| grep /| awk '{print $5}'`
use_percent=`echo $use_disk|cut -d% -f1`
#提取内存剩余空间:
avail_mem=`free | awk 'NR==2{print $NF}'`
total_mem=`free | awk 'NR==2{print $2}'`
avail_percent=`echo "scale=2;$avail_mem/$total_mem"|bc |cut -d. -f2`
#注意磁盘提取的数值的那位是kb,内存提取的的那位是mb
if [ $use_percent -gt 90 ];then
echo "mail content: root part usage is ${user_disk}, lower than 10%, please handle it!!!"
fi
if [ $avail_percent -lt 30 ];then
echo "mail content: avail_mem is ${free_percent}%, lower than 30%"
fi
#根据操作系统不同进行yum源优化centos6,centos7,centos8
mv /etc/yum.repos.d/CentOS-Bsae.repo /etc/yum.repos.d/CentOS-Base.repo.backup &>/dev/null
var=$(awk '{print $(NF-1)}' /etc/redhat-release) #拿到当前系统的版本号
os_version=`echo ${var%%.*}` #从后面开始删,把点后面的内容全删除,而且是贪婪匹配所以删到最前面那个点
if [ $os_version -eq 7 ];then
wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo &>/dev/null
elif [ $os_version -eq 6 ];then
wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-6.repo &>/dev/null
elif [ $os_version -eq 8 ];then
wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-8.repo &>/dev/null
else
echo "please check your system information"
fi
#case案例1
read -p "username:" -t 5 username
echo
if [ -z $username ];then #-z表示为空
username="default"
fi
case $username in
root)
echo "administrator"
;;
egon)
echo "common user"
;;
default)
echo "default user"
;;
*)
echo "other users"
esac
#case 案例2
read -p ">>>: " BOOLEAN
case $BOOLEAN in
[yY][eE][sS])
echo '11111111Thanks' $BOOLEAN
;;
[yY]|[nN])
echo '222222222Thanks' $BOOLEAN
;;
'T'|'F')
echo '33333333333Thans' $BOOLEAN
;;
[Tt]rue|[Ff]alse)
echo '444444444Thanks' $BOOLEAN
;;
*)
exit 1
;;
esac
#编写nginx启动脚本
. /etc/init.d/functions
if [ $# -ne 1 ];then # $#的用法是检查传给这个脚本的参数个数,个数不等一的时候执行以下操作
echo "USAGE $0 {start|stop|restart}" #打印使用方法
exit 1
fi
if [ "$1" == "start" ];then
action "start nginx" /bin/true
elif [ "$1" == "stop" ];then
action "stop nginx" /bin/true
elif [ "$1" == "restart" ];then
action "restart nginx" /bin/true
else
echo "USAGE $0 {start|stop|restart}"
exit1
fi
#编写nginx启动脚本2
netstat -lntup|grep ":80\b"
args=$1
fun(){
[ $? -eq 0 ] && action "Nginx $args is " /bin/true || echo "Nginx $args is " /bin/false
}
case $1 in
start)
netstat -an | grep -i Listen | grep -q "\b80\b" #-i忽略大小写,-q前台不显示
if [ $? -eq 0 ]
then
echo "Nginx is running ..."
else
/usr/sbin/nginx
fun
fi
;;
stop)
/usr/sbin/nginx -s stop
fun
;;
reload)
/usr/sbin/nginx -s reload
fun
;;
restart)
netstat -lntup|grep ":80\b" &>/dev/null
if [ $? -ne 0 ]
then
/usr/sbin/nginx
[ $? -eq 0 ] && echo "Nginx start is ok" || echo "Nginx start is failed"
else
/usr/sbin/nginx -s stop
[ $? -eq 0 ] && echo "Nginx stop is ok" || echo "Nginx stop is failed"
sleep 2
/usr/sbin/nginx
fun
fi
;;
status)
netstat -lntup|grep ":80\b" &>/dev/null
if [ $? -eq 0 ]
then
echo "Nginx is running ..."
else
echo "Nginx is not running ..."
fi
;;
*)
echo "Usage: $0 {start|stop|status|restart|reload}"
exit 2
esac
#编写一个简单跳板机脚本
cat<<EOF
1. BACKUP 10.0.0.41
2. WEB02 192.168.12.21
3. WEB03 10.0.0.9
EOF
trap "echo 不要乱按键盘,否则服务器将会爆炸" HUP INT TSTP
while true
do
read -p "请输入连接主机编号信息:" num
read -p "请输入账号:" user
# read -p "请输入要执行的命令:" cmd
case $num in
1)
ssh $user@10.0.0.41
[ $? -ne 0 ] && echo "connect faild"
;;
2)
ssh $user@192.168.12.21
[ $? -ne 0 ] && echo "connect faild"
;;
*)
echo "请输入链接主机的信息"
esac
done
#编写脚本,获取统计当日访问排名前十的ip地址,然后加入iptables禁用。上述脚本结合计划任务, 每3分钟执行一次
#日志文件路径
LOG_FILE="/var/log/nginx/access.log"
#获取当日日期
TODAY=$(date +"%d/%b/%Y")
#使用awk提取当日日志并统计IP,选出访问次数前10的ip,$4 ~ today就是匹配一行的第四个字段是不是today
IPS=$(awk -v today="$TODAY" '$4 ~ today {print $1}' $LOG_FILE | sort | uniq -c |sort -nr | head -n 10 | awk '{print $2}')
#将排名前10的IP加入iptabels禁用
for ip in $IPS;
do
iptables -A INPUT -s $ip -j DROP
echo "$ip has been blocked."
done
*/3 * * * * /path/script.sh
#跳板机
arr=([1]:"1.1.1.1" [2]:"2.2.2.2" [3]:"3.3.3.3" [4]:"192.168.1.111")
while true
do
cat<<EOF
1 backup 1.1.1.1
2 web01 2.2.2.2
3 web02 3.3.3.3
4 db01 192.168.1.111
5 quit
EOF
read -p "input the num of host" num
case $num in
1)
echo "${arr[$num]}"
2)
echo "${arr[$num]}"
3)
echo "${arr[$num]}"
4)
ssh root@"${arr[$num]}"
5)
break
*)
echo "please enter correct number"
esac
done
#用while循环和case来制作一个菜单
echo "script name: ${ basename $0}" #Basenam 取运行的命令名称,不包含目录
echo "version 1.0"
echo `date +%F_%H:%M:%S`
echo "Author:egon"
while read -p "(h for help):" var
do
case $var in
cpu|CPU)
echo -e "\n\n" #-e选项是可以解释\n这些转义字符
grep 'model name\|cpu MHz\| processor' /proc/cpuinfo |sort |uniq
echo -e "\n\n"
;;
mem|MEM)
echo -e "\n\n"
free
echo -e "\n\n"
;;
disk|DISK)
echo -e "\n\n"
df -Th
echo -e "\n\n"
;;
help|HELP)
echo -e "\n\tcommand\taction\n\n"
for i in cpu mem disk
do
echo -e "\t$i\t${i}_info"
done
echo -e "\thelp\tthis help page..."
echo -e "\tquit\texit !!.."
echo -e "\n\n"
;;
q|quit|exit)
exit
;;
*)
echo -e "\n$var Enter Error...\n"
esac
done
#编写监控脚本,如果根分区剩余空间小于10%,内存可用空间小月30%,就向管理员发送警告邮件,邮件内容包含相关信息
use_disk =`df /|grep / | awk '{print $5}'`
use_percent=`echo $use_disk|cut -d% -f1`
avail_mem=`free|awk 'NR==2{print $NF}'`
total_mem=`free|awk 'NR==2{print $2}'`
avail_percent=`echo "scale=2;$avail_mem/$total_mem"|bc|cut -d. f2`
if [ $use_percent -gt 90 ];then
echo "根分区已使用${use_disk}低于10%!!"
fi
if [ $avail_percent -lt 30 ];then
echo "内存剩余${avail_percent}%,低于30%"
fi
#将当日访问次数超过800次的ip禁掉,结合计划任务3分钟执行一次
*/3 * * * * /scripts/ban_ip.sh
current_day_count_ip=$(
cat /var/log/nginx/access.log |grep `LANG="en_US.UTF-8" && date +"%d/%b/%Y"`|awk '{print $1}' | sort|uniq-c|sort -rn|awk '{print $1":"$2}'
)
for info in $current_day_count_ip;
do
count=`echo $info |cut -d:-f1`
if [ $count -lt 800 ];then
continue
fi
IP=`echo $info|cut -d: -f2`
/sbin/iptables -t filter -L -n|grep $IP # 在防火墙表上搜索有没有这条,如果有的话提示已经有了
if [ $? -eq 0 ];then
echo "IP:$IP has been band, need not do it again" >> /tmp/banip.log
continue
fi
echo "$(date '+%Y-%m-%d_%H:%M:%S') IP:$IP is over $count,BAN IT" >> /tmp/banip.log
/sbin/iptables -I INPUT -s $IP -j DROP
done
#检测ip脚本,ping.sh 1.1.1.11 可以返回成功或者失败两个结果
ping -c2 1.1.1.11 &> /dev/null
if [ $? -eq 0 ];then
echo "ok"
else
echo "failed"
fi
#并发检测某个网段所有ip
for i in {1..254}
do
(
ip_add=192.168.1.$i
ping -c1 $ip_add &> /dev/null
if [ $? -eq 0 ];then
echo 'ok'
else
echo 'failed'
fi
)&
done
#编写脚本,可以计算任意两个数的+、-、*、/的结果,要求输入的位置参数必须为2个
a=$1
b=$2
if [ $# -ne 2]; then
echo "you need input 2 numbers"
exit
fi
echo "a-b=$((a-b))"
echo "a+b=$((a+b))"
echo "a*b=$((a*b))"
echo "a/b=$((a/b))"
#编写脚本 sum.sh 111 222 333 444 传入任意个数的整数,脚本都能求和
res=0
for i in $@
do
((res+=i))
done
echo $res
#用while循环和for循环两种方式print1到5,跳过3
i=1
while [$i -eq 5 ]
do
if [$i -eq 3 ];then
((i++))
continue
fi
echo $i
(i++)
done
for i in {1..5}
do
if [$i -eq 3 ];then
((i++))
continue
fi
echo $i
(i++)
done
#编写一个跳板机,把配置信息存入配置文件。脚本执行的时候用户可以选择标号登录到目标主机
#jump.conf
0、BACKUP 1.1.1.11
1、WEB01 1.1.1.12
2、WEB02 1.1.1.14
3、DB01 192.168.71.4
4、quit
#jump.sh
ip_array=(`cat path/jump.conf|awk '{print $NF}'`)
while true
do
cat path/jump.conf
read -p "please input the NO." num
case $num in
0)
ssh root@${ip_array[$num]}
;;
1)
ssh root@${ip_array[$num]}
;;
2)
ssh root@${ip_array[$num]}
;;
3)
ssh root@${ip_array[$num]}
;;
4)
break
;;
*)
echo "please input a correct number!"
esac
done
echo "跳板机 end"
#写出成绩等级查询脚本,大于90优秀,80-90良好,70-80一般,其他不及格
read -p "Please input your score:" score
if [[ "$score" =~^[0-9]+$ ]];then
if
if [ $score -ge 90 ];then
echo "优秀"
elif [ $score -ge 80];then
echo "良好"
elif [ $score -ge 70];then
echo "一般"
else
echo "不及格"
fi
else
echo "your score should be a num!"
fi
#编写登录认证程序,输错三次密码会退出
uasename="egon"
password="123"
wrong_num=0
while true
do
read -p "input your username: " inp_username
read -p "input your password: " inp_password
if [ "$inp_username" = "$username" -a "$inp_password" = "$password"];then
echo "login successful"
break
else
echo "wrong username or password"
let fail_num++
fi
if [ $fail_num -eq 3];then
echo "input too many wrong username or password, program will quit now!"
break
fi
done
#编写检测url联通性的程序,url访问三次失败则判定为失败,访问成功一次就判定成功
if [ $# -ne 1];then
echo "usage: $0 '+' url"
exit
fi
fail_num=0
while true
do
code=`curl -l -s $1 | awk 'NR==1{print $2}'`
if [ "$code" = "200" ];then
echo "$1 is ok"
break
else
let fail_num++
echo "fail_num: $fail_num"
fi
if [$fail_num -eq 3];then
echo "$1 is error"
break
fi
done
#编写脚本,命令行传入一个目录,统计出这个目录下目录文件,普通文件,软连接文件,其它文件的个数
check_dir=$1
d=0
f=0
l=0
o=0
for filename in `ls $check_dir`
do
file_path="$check_dir/$filename"
if [ -d $file_path];then
let d++
elif [ -f $file_path];then
let f++
elif [ -L $file_path];then
let l++
else
let o++
fi
done
echo "目录文件个数:$d"
echo "普通文件个数:$f"
echo "连接文件个数:$l"
echo "其他文件个数:$o"
# 编写脚本,命令行可以传入任意数量的文件路径,脚本处理后输出每个文件的文件类型
for filename in "$@"
do
if [ -d $filename];then
echo "$filename是一个目录"
elif [ -f $filename];then
echo "$filename是一个普通文件"
elif [ -b $filename];then
echo "$filename是一个块文件"
else
echo "$filename是一个未知文件"
fi
done
#判断80端口是否开启,开启输入ok,未开启就重启httpd服务,并且一次重启的状态输出成功或失败
netstat -na|grep LISTEN|grep '\b80\b' &>/dev/null
if [ $? -eq 0 ];then
echo "port 80 has openned"
else
echo "port 80 closed"
echo "port 80 is restarting now..."
systemctl restart httpd &>/dev/null
if [ $? -eq 0 ];then
echo "restart succeful"
else
echo "restart failed"
fi
fi
#编写nginx管理脚本,命令如下
#nginx_manager.sh start
#nginx_manager.sh stop
#nginx_manager.sh restart
#nginx_manager.sh reload
if [ $# -ne 1 ];then
echo "Usage: $0 start|stop|reload|restart|status" #先判断命令是否符合只有1个参数
exit
fi
args=$1 # 获取参数
function f1(){ #判断命令是否执行成功
if [ $? -eq 0 ];then
echo "nginx $args successful"
else
echo "nginx $args failed"
fi
}
case $1 in
start)
netstat -na|grep -wq "80" # 先通过判断端口是否已经被使用,确认nginx服务有没有打开
if [ $? -eq 0];then
echo "nginx is already running"
else
/usr/local/nginx/sbin/nginx &>/dev/null
f1
fi
;;
stop)
/usr/local/nginx/sbin/nginx -s stop &>/dev/null
f1
;;
reload)
/usr/local/nginx/sbin/nginx -s reload &>/dev/null
f1
;;
restart)
netstat -na|grep ":80\b" &>/dev/null
# 1. 先关闭
if [ $? -eq 0 ];then
/usr/local/nginx/sbin/nginx -s stop
fi
sleep 2 #防止还没关闭完就马上启动起不来
# 2. 再启动
/usr/local/nginx/sbin/nginx
# 3. 最后判断是否启动
f1
;;
status)
/usr/local/nginx/sbin/nginx -s status &>/dev/null
;;
*)
echo "Usage: $0 start|stop|reload|restart|status"
esac
# 编写猜数字程序,最多猜错3次,猜对了显示猜对了,大了提示猜大了,小了提示猜小了
num=`echo $((RANDOM%100+1))`
count=0
while:
do
[ $count -eq 3] && echo "guess a wrong number 3 times, quit!" && exit
read -p "input a number in the range of 1-100: "x
[[ ! $x=~ ^[0-9]+$ ]] && echo "must be a number!" && continue
if [ $x -gt $num ];then
echo "too big"
elif [ $x -lt $num ];then
echo "too small"
else
echo "correct!"
break
fi
let count++
done
#用expect免交互创建连接,迭代1
#! /bin/bash
user=$1
ip=$2
password=$3
expect<<EOF
spawn ssh $user@$ip
expect {
"yes/no"{send "yes\n";exp_continue}
"pass* {send "$password\n"}"
}
expect {
"\#" {send "ls\n"}
}
expect {
"\#" {send "exit\n"}
}
expect EOF
EOF
#用expect免交互创建连接,迭代2 循环创建连接
#实验以前先删除本机的公钥,并重新创建密钥对
rm -rf /root/.ssh/*
ssh-keygen
for ip in 192.168.1.111 192.168.1.103
do
expect<<EOF
spawn ssh-copy-id -i root@$ip
expect {
"yes/no" {send "yes\n";exp_continue}
"password" {send "abcd@1234\n"}
}
expect eof
EOF
done
#用expect免交互创建连接,迭代3 使用配置文件
#实验以前先删除本机的公钥,并重新创建密钥对
# host_info.txt:
user1:password1:1.1.1.1
user2:password2:2.2.2.2
user3:password3:3.3.3.3
# host_connect.sh
for host_info in `cat host_info.txt`
do
username=$(echo $host_info|awk -F:'{print $1}')
password=$(echo $host_info|awk -F:'{print $2}')
ip_addr=$(echo $host_info|awk -F:'{print $3}')
expect<<EOF
spawn ssh-copy-id -i $username@$ip_addr
expect {
"yes/no" {send "yes\n";exp_continue}
"pass*" {send "abcd@1234\n"}
}
expect EOF
EOF
done
#用户登录最初版
#!/bin/bash
i=0
while true
do
read -p "please input your username: " inp_username
for line in `cat lock.txt`
do
lock_user=$(echo $line |cut -d: -f1)
lock_time=$(echo $line |cut -d: -f2)
if [ "$inp_username" = "$lock_user" ];then
# 判断锁定的时间,如果超过60s,应该解锁放行,否则锁定
fi
done
read -p "please input your password: " inp_password
if [ "$inp_username" = "egon" ] && [ "$inp_password" = "123" ];then
echo "welcome to home page!!!"
# 放登录成功之后要执行的代码!!!
break
else
echo "username or password input error"
let i++
fi
if [ $i -eq 3 ];then
echo "try too many times,break!!!"
echo "$inp_username:$(date '+%s')" >> lock.txt
fi
done
#用户登录改进版
[root@www.egonlin.com /scripts]# cat login.sh
#!/bin/bash
function lock_test() {
for line in `cat lock.txt`
do
lock_user=$(echo $line |cut -d: -f1)
lock_time=$(echo $line |cut -d: -f2)
if [ "$inp_username" = "$lock_user" ];then
# 判断锁定的时间,如果超过60s,应该解锁放行,否则锁定
current_time=$(date '+%s')
period=$((current_time-lock_time))
if [ $period -le 60 ];then
# 处于锁定周期内
echo "用户处于锁定状态。。。"
return 1
else
# 应该解锁,继续进行后续认证环节
return 0
fi
fi
done
}
i=0
while true
do
read -p "please input your username: " inp_username
lock_test
if [ $? -ne 0 ];then
echo "==============================="
continue
fi
read -p "please input your password: " inp_password
if [ "$inp_username" = "egon" ] && [ "$inp_password" = "123" ];then
echo "welcome to home page!!!"
# 放登录成功之后要执行的代码!!!
break
else
echo "username or password input error"
let i++
fi
if [ $i -eq 3 ];then
echo "try too many times,break!!!"
echo "$inp_username:$(date '+%s')" >> lock.txt
fi
done
#用户登录最终版
[root@www.egonlin.com /scripts]# cat login.sh
#!/bin/bash
function lock_test() {
for line in `cat lock.txt`
do
lock_user=$(echo $line |cut -d: -f1)
lock_time=$(echo $line |cut -d: -f2)
if [ "$inp_username" = "$lock_user" ];then
# 判断锁定的时间,如果超过60s,应该解锁放行,否则锁定
current_time=$(date '+%s')
period=$((current_time-lock_time))
if [ $period -le 60 ];then
# 处于锁定周期内
echo "用户处于锁定状态。。。"
return 1
else
# 应该解锁,继续进行后续认证环节
sed -ri "/^\b($inp_username)\b/d" lock.txt
lock_user_info[$k]=0
return 0
fi
fi
done
}
declare -A lock_user_info
while true
do
read -p "please input your username: " inp_username
lock_test
if [ $? -ne 0 ];then
echo "==============================="
continue
fi
read -p "please input your password: " inp_password
if [ "$inp_username" = "egon" ] && [ "$inp_password" = "123" ];then
echo "welcome to home page!!!"
# 放登录成功之后要执行的代码!!!
break
else
echo "username or password input error"
let lock_user_info[$inp_username]++
fi
declare -A |grep lock_user_info
for k in ${!lock_user_info[@]};
do
username=$k
grep -q "^\b$username\b" lock.txt
if [ $? -eq 0 ];then
continue
fi
error_times=${lock_user_info[$k]}
if [ $error_times -ge 3 ];then
echo "try too many times,break!!!"
echo "$username:$(date '+%s')" >> lock.txt
fi
done
done
暂无评论