一:ping ip
#!/usr/bin/bash
#this is test ip
#owner by rocy 2020/9/21
ip=10.9.62.124
ping -c1 $ip &>/dev/null && echo"$ip is up" || echo "$ip is down"
二:ping ip if判断
#!/usr/bin/bash
#!/usr/bin/bash
#this is test2 ip
#by rocy 2020/9/21
ip=10.9.62.124
if ping -c1 $ip &>/dev/null ;then
echo "$ip is up"
else
echo "$ip is down"
fi
三:位置参数
#!/bin/bash
#!/usr/bin/bash
echo 我的第一个参数是:$1
echo 我的第二个参数是:$2 hahaha
echo 我的第三个参数是:$3
echo 我的第四个参数是:$4
echo 一共有几个参数呢:$#
四:ping ip
#!/usr/bin/bash
ping -c1 $2 &>/dev/null
if [ $? -eq 0 ] ;then
echo "$2 is up"
else
echo "$2 is down"
fi
五:预定义变量
#!/usr/bin/bash
#获取主机信息
time=`date +%F-%T` `date +%F`:显示当前日期 -:加的格式 %T:时间
echo "现在的时间是:" $time
echo "当前的用户是" $USER
echo "当前的用户标识" $UID
echo "当前的主机名称是" $HOSTNAM
六:交互
#!/usr/bin/bash
#read -p "请输入姓名:" name
#read -p "请输入性别:" sex
#read -p "请输入年龄:" age
#echo "哈哈哈 $name 的性别是$sex 年龄是$age"
#read -p "请输入您的姓名" name
#read -p "请输入您管理的IP地址" ip
#echo "IP$ip 的管理员是$name "
#read -p "请输入姓名 性别 年龄:" name sex age
#echo "您的姓名是$name 性别是$sex 年龄是$age"
read -p "你中午想吃啥 米? 面? 饺子?" r n d
echo "哦吼,你想吃$r $n $d 呀"
七:备份
#!/bin/bash
read -p "请输入您的备份目录" back_dir1
mkdir $back_dir1 &>/dev/null
if [ $? -eq 0 ] ;then
echo "create successful"
else
echo "$back_dir1 is already created"
fi
八:当前内存使用百分比
#!/usr/bin/bash
mem_used=`free -m | grep Mem |awk '{print $3}'`
mem_total=`free -m | grep Mem |awk '{print $2}'`
mem_percent=$(($mem_used*100/$mem_total))9
a=2
b-13
echo "$a和$b的和是:$(( $a + $b ))"
echo "$a和$b的积是:$(( $a * $b ))"
echo "$a和$b的差是:$(( $a - $b ))"
echo "$a和$b的商是:$(( $a / $b ))"
十:ping www.baidu.com 如果通了 请将通的日期及时间写入到 monitor.up.txt
#!/usr/bin
ping -c1 www.baidu.com &>/dev/null
if [$? -eq 0] ;then
echo "$(date +'%Y-%m-%d %H:%M:%S) - run monitor program www.baidu.com is ok" > /var/log/up.txt
else
echo "$(date +'%Y-%m-%d %H:%M:%S) - run monitor program www.baidu.com is down" > /var/log/down.txt
fi
十一:备份
#!/bin/bash
back_dir=/var/mysql_back
if ! test -d $back_dir;then
mkdir -p $back_dir
fi
echo "开始创建,并且备份了。。"
十二:字符串比较
#!/bin/bash
if [ $UID -ne 0 ];then //if [ $UID != "root" ];then
echo "你没有权限"
exit //退出脚本
fi
yum -y install httpd
十三:文件已存在,显示文件信息,文件不存在,开始创建
#!/bin/bash
if [ -f /tmp/test.txt ] ;then
echo "文件已存在,显示文件信息"
sleep 1 //沉睡几秒
ls -l /tmp/test.txt
else
echo "文件不存在,开始创建"
sleep 1
touch /tmp/test.txt
echo "创建成功"
fi
十四:for循环添加用户
#!/bin/bash
for i in {1..10}
do
echo "正在添加用户abc$i,稍等。。。"
sleep 1
useradd abc$i
echo "用户abc $i 添加成功!正在设置密码请稍等。。。"
sleep 1
echo "123" | passwd --stdin abc$i > /dev/null
if [ $? -eq 0 ];then
echo "用户abc$i 的密码设置成功,可以正常登陆!"
fi
done
十五:交互式添加用户 修改密码
#!/bin/bash
read -p "PLS input a username :" user
read -p "PLS input a new password :" passwd
id $user &> /dev/null
if [ $? -eq 0 ];then
echo "user $user exists"
echo $passwd | passwd --stdin $user &>/dev/null
echo "user $user 密码成功修改"
else
useradd $user
if [ $? -eq 0 ];then
echo "user is created"
echo $passwd | passwd --stdin $user &>/dev/null
echo "user $user 密码已设定成功"
sleep 3
fi
fi
十六:交互安装KVM
#!/bin/bash
read -p "请确认开始安装KVM [y/n]" kvm_install
if [ ! "$kvm_install" = "y" ];then
# echo -e "$red_col 输入不正确!$reset_col"
echo -e "输入不正确"
exit
else
echo "开始安装服务啦"
yum -y install kvm
fi
把do 后面的动作加上 {}& 实现脚本多进程运行
十七:找出可以ping通的ip
#!/bin/bash
src_ip="10.9.62"
for i in {2..254}
do
ping -c1 $src_ip.$i &>/dev/null
if [ $? -eq 0 ];then
echo "alive:$src_ip.$i" >> ip_up.txt
echo "alive:$src_ip.$i"
else
echo "down:$src_ip.$i" >> ip_down.txt
echo "down:$src_ip.$i"
fi
done
sleep 1
echo "finish"
十八:修改文件后缀
#!/bin/bash
for name in `ls *.html`
do
mv $name ${name%.html}.txt
done
十九:监控域名存活
#!/usr/bin/bash
URLLIST=$(egrep "com|cn" ./url.txt) ./ 当前目录
for url in ${URLLIST}
do
statuCode=$(curl -I --connect-timeout 3 -m 10 -s "${url}" | grep "HTTP")
if [[ ${statuCode: 9: 3} -eq 200 ]] || [[ ${statuCode: 9: 3} -eq 302 ]];then
echo "$(date +'%Y-%m-%d %H:%M:%S') - run monitor program ${url} is ok" >>/var/log/urlMonitor.log
else
echo "$(date +'%Y-%m-%d %H:%M:%S') - run monitor program ${url} is failed" >>/var/log/urlerrorMonitor.log
echo "[ERROR] ${url} Downtime! Please repair."
fi
done
二十:选择
#!/bin/bash
read -p "pls input a number :" n
case "$n" in
1)
echo "变量是1"
;;
2)
echo "变量是2"
;;
3)
echo "变量是3"
;;
*)
echo "请重新输入1-3"
exit
esac
二十一:跳板机
#!/bin/bash
#server
web1=10.9.62.124
web2=10.9.62.80
cat <<-EOF
1.web1
2.web2
EOF
read -p "input your number :" num
case "$num" in
1)
ssh root@$web1
;;
2)
ssh root@$web2
;;
esac
二十二:多条件判断
#!/bin/bash
read -p "pls input score to test level:" score
if [ $score -ge 90 ];then
echo "优秀"
elif [ $score -ge 80 ];then
echo "良好"
elif [ $score -ge 70 ];then
echo "中等"
elif [ $score -ge 60 ];then
echo "及格"
else
echo "不及格"
fi
二十三:删除用户
#!/bin/bash
read -p "which you wangt to deleted user:" user
id $user &>/dev/null
if [ $? -ne 0 ];then
echo "no such user:$user"
exit
fi
read -p "Are you sure?[y/n]:" action
if [ "$action" = "y" ];then
userdel -r $user
echo "user is already deleted"
else
echo "good!"
fi
二十四:系统工具箱
#!/bin/bash
cat << EOF
m|M) show memory usages;
d|D) show disk usages;
q|Q) quit
EOF
read -p "Your choice " choice
case $choice in
m|M)
free -m
;;
d|D)
df -h
;;
q|Q)
exit
;;
c|C)
echo 3 > /proc/sys/vm/drop_caches
echo "已释放缓存"
;;
*)
echo "Invalid input"
;;
esac
二十五:while测试ip在线
#!/bin/bash
i=2
while [ $i -le 254 ]
do
{
ip=10.9.62.$i
ping -c1 -W1 $ip &>/dev/null
if [ $? -eq 0 ];then
echo "$ip up"
fi
}&
let i++
done
二十六:输入1-5,while,case,break
#!/bin/bash
while :
do
echo -n "Input a number between 1 to 5: "
read aNum
case $aNum in
1|2|3|4|5)
echo "Your number is $aNum"
;;
*)
echo "You do not select a number between 1 to 5,game is over!"
break //跳出循环体
;;
esac
done
二十七:计算size总额
#!/bin/bash
for size in $(ls -l *.html |awk '{print$5}')
do
sum=$(($sum+$size))
done
echo $sum
二十八:安装lamp 调取其他脚本
#!/bin/bash
while :
do
cat <<-EOF
|-----------------|
| 1.install lamp |
| 2.install lnmp |
| 3.exit |
|-----------------|
EOF
#read -t 3 -p "Please input tut the num you want:" a
read -p "Please input tut the num you want:" a
case $a in
1)
if [ -f lamp.sh ];then
chmod 777 lamp.sh
./lamp.sh
sleep 3
echo "lamp is installed!"
else
echo "no lamp.sh"
fi
;;
2)
if [ -f lnmp.sh ];then
chmod 777 lnmp.sh
./lnmp.sh
sleep 3
echo "lnmp is installed!"
else
echo "no lnmp.sh"
fi
;;
3)
exit
;;
*)
echo "输入错误"
;;
esac
echo "---------------------我是可爱的分割线喵呜-----------------------"
done
二十九:定义函数
#!/bin/bash
demoFun(){ //定义函数
echo "这是我的第一个shell函数"
}
echo "-----函数开始执行-----"
demoFun //调用函数
echo "-----函数执行完毕-----"
三十:调取两个函数
#!/usr/bin/bash
function zh () {
echo "我是晗哥!"
}
function zs () {
echo "我是张三!"
}
zh
zs
三十一:函数传参
#!/bin/bash
function eat () {
echo "中午吃: $1"
}
eat $1
三十二:计算两个数之和
#!/bin/bash
fun(){
echo "这个函数会对输入的两个数字进行相加运算"
echo "请输入第一个数字"
read aNum
echo "请输入第二个数字"
read anotherNum
echo "两个数字分别为 $aNum 和 $anotherNum"
return $(($aNum+$anotherNum))
}
fun
echo "您输入的两个数字之和为$? "
三十三:查看有多少个用户
#!/bin/bash
function get_users ()
{
users=`cat /etc/passwd | cut -d: -f1`
echo $users
}
//定义一个变量将获取用户列表赋值给这个变量
user_list=`get_users`
index=1
for u in $user_list
do
echo "the $index user is : $u"
index=$(($index+1))
done
三十四:测试vsftpd是否运行
#!/bin/bash
function is_vsftpd_running ()
{
ss -tnlp | grep vsftpd &> /dev/null
if [ $? -eq 0 ];then
return 0 //结束
else
return 1 //结束但是函数失败
fi
}
is_vsftpd_running && echo "vsftpd is running" || echo "vsftpd is stopped"
三十五:检测CPU是否异常
#!/bin/bash
DATE=$(date +%F" "%H:%M)
IP=$(ifconfig |grep broadcast |awk '{print $2}')
if !which vmstat &>/dev/null;then
echo "vmstst command no found.Please install procps package"
exit 1
fi
US=$(vmstat |awk NR==3'{print $13}')
SY=$(vmstat |awk NR==3'{print $14}')
IDLE=$(vmstat |awk NR==3'{print $15}')
WAIT=$(vmstat |awk NR==3'{print $16}')
USE=$(($US+$SY))
if [ $USE -ne 1 ];then
echo "
Date: $DATE
Host: $IP
Problem: CPU utilization $USE "
fi
三十六:检测网络 yum源 连通性
#!/bin/bash
check_net(){
echo "正在检查网络通信"
ping -c1 www.baidu.com &>/dev/null
if [ $? -eq 0 ];then
echo "你的网络是没有问题的"
else
echo "你的网络有问题,请先检查网络"
exit
fi
}
check_net
echo "++++++++++++++++++++++++++++++++"
check_yum(){
echo "正在检查yum源是否可用"
yum repolist
if [ $? -eq 0] ;then
echo "你的yum源可以正常使用"
else
echo "yum源不能用,请手动配置网络yum源"
exit 3
fi
}
check_yum
echo "++++++++++++++++++++++++++++++++++"
三十七:嵌套函数
#!/bin/bash
fact(){
fact=1
for ((i=1;i<=5;i++))
do
fact=$[$fact * $i]
done
echo "5的阶乘是:$fact"
}
fact
三十八:数字加倍
#!/bin/bash
double(){
read -p "please input a num: " num
return $[2*$num]
}
double
echo "double num is: $?"
三十九:数组引用
#!/bin/bash
NAME[0]="BJ"
NAME[1]="SH"
NAME[2]="SZ"
NAME[3]="GZ"
NAME[4]="HZ"
NAME[5]="ZZ"
echo "First Index: ${NAME[0]}"
echo "Second Index: ${NAME[1]}"
echo "Sixth Index: ${NAME[5]}"
四十:数组访问
#!/bin/bash
array=(gz cloud 19)
echo "case 1"
for line in "${array[@]}"
do
echo $line
done
echo "case 2"
for line in "${array[*]}"
do
echo "$line"
done
echo "case 3"
for line in ${array[*]}
do
echo "$line"
done
四十一:配置bond
#!/bin/bash
echo "此脚本用来配置bond"
read -p "请问是否开始执行?[y/n]" action
if [ "$action" = "y" ];then
cat > /etc/sysconfig/network-scripts/ifcfg-bond0 <<-EOF
DEVICE=bond0
TYPE=Ethernet
ONBOOT=yes
NM_CONTROLLED=no
BOOTPROTO=none
IPADDR=10.9.62.124
PREFIX=24
IPV6INIT=no
USERCTL=no
BONDING_MASTER=yes
BONDING_OPTS="mode=6 miimon=100"
EOF
sed -ri 's/BOOTPROTO="dhcp"/BOOTPROTO="none"/' /etc/sysconfig/network-scripts/ifcfg-eth0
sed -ri '/^IPV6/d' /etc/sysconfig/network-scripts/ifcfg-eth0
sed -ri '5a\NM_CONTROLLED=no' /etc/sysconfig/network-scripts/ifcfg-eth0
sed -ri '5a\USERCTL=no' /etc/sysconfig/network-scripts/ifcfg-eth0
sed -ri '5a\MASTER=bond0' /etc/sysconfig/network-scripts/ifcfg-eth0
sed -ri '5a\SLAVE=yes' /etc/sysconfig/network-scripts/ifcfg-eth0
cat > /etc/sysconfig/network-scripts/ifcfg-eth1 <<-EOF
DEVICE=eth1
TYPE=Ethernet
ONBOOT=yes
NM_CONTROLLED=no
BOOTPROTO=none
IPV6INIT=no
USERCTL=no
MASTER=bond0
SLAVE=yes
EOF
systemctl restart network
if [ $? -eq 0 ];then
echo "配置bond成功~"
else
echo "配置bond失败,请检查是否存在两个网卡"
exit
fi
else
echo "那你打开我干啥,哼嘤嘤嘤"
exit 3
fi
四十二:配置虚拟主机,选1为博客,2为论坛
#!/bin/bash
env(){
yum -y install mariadb mariadb-server mariadb-libs php php-mysql php-gd php-fpm php-cli gd httpd &>/dev/null
systemctl restart httpd mariadb &>/dev/null
if [ $? -eq 0 ];then
echo "数据库程序已安装"
else
echo "数据库程序未安装"
exit 2
fi
mysqladmin -uroot password "123" &>/dev/null
if [ $? -eq 0 ];then
echo "数据库初始密码为123"
else
echo "数据库初始密码设置失败,请手动设置"
fi
mysql -u root -p123 <<-EOF &>/dev/null
create database shuju;
EOF
if [ $? -eq 0 ];then
echo "已创建数据库,名为shuju"
else
echo "数据库创建失败,请手动创建"
fi
}
luntan(){
cat > /etc/httpd/conf.d/tianyun.conf <<-EOF
<VirtualHost *:80>
ServerName www.luntan.com
DocumentRoot /web/luntan
</VirtualHost>
<Directory "/web/luntan">
Require all granted
</Directory>
EOF
mkdir -p /web/luntan
yum -y install unzip &>/dev/null
unzip Discuz_X3.4_SC_UTF8.zip &>/dev/null
cp -rf wordpress/* /web/luntan &>/dev/null
chmod -R 777 /web/
}
boke(){
cat > /etc/httpd/conf.d/tianyun.conf <<-EOF
<VirtualHost *:80>
ServerName www.boke.com
DocumentRoot /web/boke
</VirtualHost>
<Directory "/web/boke">
Require all granted
</Directory>
EOF
mkdir -p /web/boke
tar xf wordpress-4.7.2-zh_CN.tar.gz &>/dev/null
cp -rf wordpress/* /web/boke &>/dev/null
chmod -R 777 /web/
}
check(){
if [ $? -eq 0 ];then
echo "创建成功"
else
echo "创建失败"
fi
}
while :
do
cat <<-EOF
|----------我是可爱的小方框---------|
| |
| [1] 安装博客 |
| [2] 安装论坛 |
| 输入其他会退出程序 |
| |
|------------(* ̄∇ ̄*)-----------|
EOF
read -p "请选择您想进行的操作: " a
case $a in
1)
env
boke
check
;;
2)
env
luntan
check
;;
*)
exit
;;
esac
echo "+++++++++++++++++++++++++++++++++++++"
done
四十三:A-B expect SSH
#!/usr/bin/expect
spawn ssh-keygen
expect {
".ssh/id_rsa):" { send "\r"; exp_continue }
"Overwrite (y/n)?" { send "y\r"; exp_continue }
"no passphrase):" { send "\r"; exp_continue }
"again:" { send "\r" };
}
interact
spawn ssh-copy-id -i 188.131.132.198
expect {
"(yes/no)?" { send "yes\r"; exp_continue }
"password:" {l
#!/bin/bash
read -p "请输入一个数值:" num
if [[ ! "$num" =~ ^[0-9]+$ ]];then
echo "你输入的不是数字,程序退出"
else
echo "你输入的是$num "
fi
四十四:CPU监控报警脚本
- -us:非内核进程消耗CPU运算时间的百分比
- -sy:内核进程消耗CPU运算时间的百分比
- -id:空闲CPU的百分比
- -wa:等待I/O所消耗的CPU百分比
- -st:被虚拟机所盗用的CPU百分比
#!/usr/bin/env bash
#
# author: zhaohan
# date: 2020/09/23
# usage: monitor cpu status
DATE=$(date +'%Y-%m-%d %H:%M:%S')
IPADDR=$(ifconfig | grep inet | awk 'BEGIN{ FS=" " }NR==1{ print $2 }')
ipaddr=$(ifconfig | awk 'NR==2{print $2}')
MAIL="bavduer@163.com"
# 检测vmstat命令是否存在
if ! which vmstat &>/dev/null; then
yum -y install procps-ng &>/dev/null
if [ $? -eq 0 ];then
echo "vmstat already installed"
fi
fi
US=$(vmstat | awk 'BEGIN{ FS=" " }NR==3{ print $13 }')
SY=$(vmstat | awk 'BEGIN{ FS=" " }NR==3{ print $14 }')
ID=$(vmstat | awk 'NR==3{ print $15 }')
WA=$(vmstat | awk 'NR==3{ print $16 }')
ST=$(vmstat | awk 'NR==3{ print $17 }')
useTotal=$((${US}+${SY}))
if [[ ${useTotal} -ge 70 ]];then
echo "
Date: ${DATE}
Host: ${HOSTNAME}: ${IPADDR}
Problem: CPU using rate: ${useTotal}%
" | mail -s "CPU Monitor Warnning" ${MAIL}
fi
四十五:免密
#!/usr/bin/bash
get_keygen (){
/usr/bin/expect <<-EOF &>/dev/null
spawn ssh-keygen
expect {
".ssh/id_rsa):" { send "\n" ; exp_continue }
"Overwrite (y/n)?" { send "y\n" ; exp_continue }
"no passphrase):" { send "\n" ; exp_continue }
"again:" { send "\n" } ;
}
expect eof
EOF
}
send_key (){
/usr/bin/expect <<-EOF &>/dev/null
spawn ssh-copy-id root@$ip
expect {
"yes/no" { send "yes\n" ; exp_continue }
"password:" { send "1\n" ; exp_continue }
}
expect eof
EOF
}
get_keygen
for ip in $(cat ./ip.txt)
do
send_key $ip
echo "$ip已发送"
done