shell编程程序实例
1、计算器
#!/bin/bash
#test
#by authors hdc 2018
function add(){ #实现加法
c=$[ $a + $b ] #相加
echo $c
}
function sub(){ #实现减法
c=$[$a - $b]
echo $c
}
function mul(){ #实现乘法
c=$[ $a * $b ]
echo $c
}
function devide(){ 实现除法
if [ $b -eq 0 ];then #判断分母是否为0
echo "分母不能为0"
read -p "请重新输入第二个操作数:" b
fi
c=$[ $a / $b ]
echo $c
}
i="ddf"
while [[ -n "$i" ]] #循环条件,即判断是否为空字符串,不是返回真
do
read -p "请输入要执行打操作:" i #人机交互,输入
if [[ -z "$i" ]];then #循环条件,即判断是否为空字符串,是返回真
echo "结束运行"
exit
fi
read -p "Please input the number1:" a
read -p "Please input the number2:" b
case $i in
add )
add
;;
sub )
sub
;;
mul )
mul
;;
devide )
devide
;;
* )
echo "输入错误,请重新输入!"
;;
esac
done
2、auto_scp.sh
#!/bin/bash
#auto scp files for client
#by authors hdc 2018
if [ ! -f ip.txt ];then
echo -e "\033[31m please create ip.txt Files\033[0m"
cat <<EOF
192.168.112.130
192.168.112.131
EOF
exit
fi
if
[ -z "$1" ];then
echo "\033[31m $0 command ,example{src_files|src_dir des_dir}\033[0m"
exit
fi
count=`cat /home/hdc/user/ip.txt | wc -l`
rm -rf ip.txt.swp
i=0
while ((i<$count))
do
i=`expr $i + 1`
sed "${i}s/^/&${i} /g" ip.txt >>ip.txt.swp
IP=`awk -v I="$i" '{if(I==$1)print $2}' ip.txt.swp`
scp -r $1 root@${IP}:$2
done
3、auto_deny_ip.sh
#!/bin/sh
#auto drop ssh failed IP address
#hdc 2018
SEC_FILE=/var/log/secure
IP_ADDR=`tail -n 1000 /var/log/secure | grep "Failed password"| egrep -o "([0-9]{1,3}\.){3}[0-9]{1,3}" | sort -nr |uniq -c | awk '$1>=4 {print $2}'`
IPTABLE_CONF=/etc/sysconfig/iptables
for i in echo $IP_ADDR
do
cat $IPTABLE_CONF | grep $i >/dev/null
if
[ $? -ne 0 ];then
sed -i "/lo/a -A INPUT -s $i -m --state NEW -m tcp -p tcp --dport 22 -j DROP" $IPTABLE_CONF
else
echo "已经存在"
fi
done
`service iptables restart`