美文网首页PHP学习笔记
Shell学习笔记-收藏的脚本

Shell学习笔记-收藏的脚本

作者: 赵客缦胡缨v吴钩霜雪明 | 来源:发表于2022-04-27 16:25 被阅读0次

    测试 192.168.4.0/24 整个网段中哪些主机处于开机状态,哪些主机处于关机 (for )

    #!/bin/bash
    for  i  in   {1..254}
    do
              ping ‐c2 ‐i0.3 ‐W1 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
    

    测试 192.168.4.0/24 整个网段中哪些主机处于开机状态,哪些主机处于关机 (while )

    #!/bin/bash
    i=1
    while  [  $i  ‐le  254 ]
    do
              ping ‐c2 ‐i0.3 ‐W1 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
    

    测试 192.168.4.0/24 整个网段中哪些主机处于开机状态,哪些主机处于关机 (多进程)

    #!/bin/bash
    #定义一个函数,ping 某一台主机,并检测主机的存活状态
    myping(){
    ping ‐c2 ‐i0.3 ‐W1 $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 第二台主机,依次类推。
    

    进度条

    #!/bin/bash
    jindu(){
    while :
    do
         echo  ‐n  '#'
         sleep 0.2
    done
    }
    jindu &
    cp  ‐a  $1  $2
    killall  $!
    echo  "拷贝完成''
    

    红色进度条

    #!/bin/bash
    
    declare -a ary
    
    for i in `seq 0 20`
    do
    
        ary[$i]=" "
        echo -en "\e[41;5m ${ary[@]}\e[;0m"
        sleep 1
    
    done
    

    进度条,动态时针版本

    #!/bin/bash
    #定义一个显示进度的函数,屏幕快速显示|  / ‐ \
    rotate_line(){
    INTERVAL=0.1                 #设置间隔时间
    COUNT="0"                   #设置 4 个形状的编号,默认编号为 0(不代表任何图像)
    while :
    do
    COUNT=`expr $COUNT + 1`          #执行循环,COUNT 每次循环加 1,(分别代表 4 中不同的形状)
    case $COUNT in                     #判断 COUNT 的值,值不一样显示的形状就不一样
    "1")                                 #值为 1 显示‐ 
              echo ‐e '‐'"\b\c"                     
              sleep $INTERVAL
              ;;
        "2")                               #值为 2 显示\\,第一个\是转义
              echo ‐e '\\'"\b\c"
              sleep $INTERVAL
              ;;
        "3")                              #值为 3 显示|
              echo ‐e "|\b\c"
              sleep $INTERVAL
              ;;
       "4")                             #值为 4 显示/
              echo ‐e "/\b\c"
              sleep $INTERVAL
              ;;
        *)                                #值为其他时,将 COUNT 重置为 0
              COUNT="0";;
        esac
    done
    }
    rotate_line
    

    使用死循环实时显示 eth0 网卡发送的数据包流量

    #!/bin/bash
    while :
    do
              echo  '本地网卡 eth0 流量信息如下: '
              ifconfig  eth0   |  grep "RX pack"  | awk  '{print $5}'
              ifconfig  eth0   |  grep "TX pack"  | awk  '{print $5}'
              sleep 1
    done
    

    使用 user.txt 文件中的人员名单,在计算机中自动创建对应的账户并配置初始密码

    #!/bin/bash
    #本脚本执行,需要提前准备一个 user.txt 文件,该文件中包含有若干用户名信息
    for  i  in  `cat  user.txt`
    do
             useradd  $i
             echo "123456" | passwd ‐‐stdin $i
    done
    

    编写批量修改扩展名脚本,如批量将 txt 文件修改为 doc 文件

    #!/bin/bash
    #执行脚本时,需要给脚本添加位置参数
    #脚本名  txt   doc(可以将 txt 的扩展名修改为 doc) #脚本名  doc  jpg(可以将 doc 的扩展名修改为 jpg)
    for  i   in   "ls *.$1"
    do
            mv  $i    ${i%.*}.$2
    done
    

    使用 expect 工具自动交互密码远程其他主机安装 httpd 软件�

    #!/bin/bash
    #删除~/.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
    

    轮询检测Apache状态并启用钉钉报警

    #!/bin/bash
    
    shell_user="root"
    shell_domain="apache"
    
    shell_list="/root/ip_list"
    shell_row=`cat $shell_list |wc -l`
    
    function trans_text(){
    text=$1
    
    curl 'https://oapi.dingtalk.com/robot/send?access_token=b4fcf5862088a1bc7f2bf66a' -H'Content-Type: application/json' -d'{      #指定钉钉机器人hook地址
                "msgtype": "text", 
                "text": {
                "content": "'"$text"'"
            }, 
    }'
    }
    
    function apache_check_80(){
        ip=$1
        URL="http://$ip/index.html"
        HTTP_CODE=`curl -o /dev/null -s -w "%{http_code}" "${URL}"`
    
        if [ $HTTP_CODE != 200 ]
            then
                trans_text "
                =================================================================
                                    \n $ip Apache 服务器状态异常,网页返回码: '"$HTTP_CODE"' 请及时处理 ! \n
                                    ================================================================= \n"
        fi
    }
    
    while true
    do
    
    shell_list="/root/ip_list"
    shell_row=`cat $shell_list |wc -l`
        for temp in `seq 1 $shell_row`
        do
                Ip_Addr=`cat $shell_list |head -n $temp |tail -n 1`
            apache_check_80 $Ip_Addr
        done
    
        sleep 10
    done
    

    一台监控主机,一台被监控主机。被监控主机分区使用率大于80%,就发告警邮件。放到crontab里面,每10分钟执行一次

    #!/bin/bash
    
    FSMAX="80"     
    remote_user='root'  
    remote_ip=(IP地址列表)  
    ip_num='0'      
    
    while [ "$ip_num" -le "$(expr ${#remote_ip[@]} -l)"]  
    do  
    read_num='1'           
            ssh "$remote_user"@"${remote_ip[$ip_num]}"  df -h > /tmp/diskcheck_tmp
            grep '^/dev/*'  /tmp/diskcheck_tmp | awk '{print $5}'|sed 's/\%//g'  > /tmp/diskcheck_num_tmp
    
            while [ "$read_num" -le $(wc -l < /tmp/diskcheck_num_tmp) ]  
            do
                    size=$(sed -n "$read_num" 'p'  /tmp/diskcheck_num_tmp)
                    if [ "size" -gt "$FSMAX" ]
                    then                       
                            $(grep '^/dev/*'  /tmp/diskcheck_tmp |sed -n $read_num'p'  > /tmp/disk_check_mail)
                            $(echo ${remote_ip[$ip_num]}) >> /tmp/disk_check_mail)
                            $(mail  -s "diskcheck_alert"  admin  <  /tmp/disk_check_mail)
                    fi                         
    
                    read_num=$(expr  $read_num + 1)
            done               
    
            ip_num=$(expr  $ip_num + 1)
    done
    

    自动ftp上传

    #! /bin/bash
    
    ftp -n << END_FTP  
    open 192.168.1.22  
    user  test testing      //用户名test  密码:testing  
    binary  
    prompt  off    //关闭提示  
    mput   files     //上传files文件  
    close  
    bye  
    END_FTP
    

    mysqlbak.sh备份数据库目录脚本

    #!/bin/bash
    
    DAY=`date +%Y%m%d`
    SIZE=`du -sh /var/lib/mysql`
    echo "Date: $DAY" >> /tmp/dbinfo.txt
    echo "Data Size: $SIZE" >> /tmp/dbinfo.txt
    cd /opt/dbbak &> /dev/null || mkdir /opt/dbbak
    tar zcf /opt/dbbak/mysqlbak-${DAY}.tar.gz /var/lib/mysql /tmp/dbinfo.txt &> /dev/null
    rm -f /tmp/dbinfo.txt
    
    crontab-e
    55 23 */3 * * /opt/dbbak/dbbak.sh
    

    expect实现远程登陆自动交互

    #!/usr/bin/expect -f
    
    set ipaddress [lindex $argv 0]
    
    set passwd [lindex $argv 1]
    
    set timeout 30
    
    spawn ssh-copy-id root@$ipaddress
    
    expect {
    
    "yes/no" { send "yes\r";exp_continue }
    
    "password:" { send "$passwd\r" }
    
    }
    
    #expect "*from*"
    
    #send "mkdir -p ./tmp/testfile\r"
    
    #send "exit\r"
    
    #expect "#" #i# 命令运行完, 你要期待一个结果, 结果就是返回shell提示符了(是# 或者$)
    

    http心跳检测

    #!/bin/bash
    
    function MyInstall
    {
            if ! rpm -qa |grep -q "^$1"
            then
    
                    yum install $1
                    if [ $? -eq 0 ]
                    then
                            echo -e "$i install is ok\n"
                    else
                            echo -e "$1 install no\n"
                    fi
            else
                    echo -e "yi an zhuang ! \n"
            fi
    }
    
    for ins in mysql php httpd
    do
            MyInstall $ins
    done
    

    shell实现插入排序

    #!/bin/bash
    
    declare -a array
    
    for i in `seq 1 10`
    do
        array[$i]=$RANDOM
    
    done
    
    echo -e "Array_1:  ${array[@]}"
    
    for (( x=1;x<=9;x++ ))
    do
        for(( y=1;y<=9;y++ ))
        do
            if [ ${array[$y]} -gt ${array[$y+1]} ]
            then
                temp=${array[$y]}
                array[$y]=${array[$y+1]}
                array[$y+1]=$temp
            fi
    
        done
    
    done
    
    echo -e "Array_2:  ${array[@]}"
    

    bash实现动态进度条

    #!/bin/bash
    i=0
    bar=''
    index=0
    arr=( "|" "/" "-" "\\" )
    
    while [ $i -le 100 ]
    do
        let index=index%4
        printf "[%-100s][%d%%][\e[43;46;1m%c\e[0m]\r" "$bar" "$i" "${arr[$index]}"
        let i++
        let index++
        usleep 30000
        bar+='#'
        clear
    done
    
    printf "\n"
    

    根据文件内容创建账号

    #!/bin/bash
    
    for Uname in `cat /root/useradd.txt |gawk '{print $1}'`
    do
    
                    id $Uname &> /dev/null
                    if [ $? -eq 0 ]
                    then
                            echo -e "这个账号已存在!来源:微信公众号【网络技术干货圈】"
                            continue
                    fi
            for Upasswd in `cat /root/useradd.txt |gawk '{print $2}'`
            do
                    useradd $Uname &> /dev/null
                    echo "$Upasswd" |passwd --stdin $Uname &> /dev/null
                    if [ $? -eq 0 ]
                    then
                            echo -e "账号创建成功!"
                    else
                            echo -e "创建失败!"
                    fi
    
            done
    
    done
    

    监控主机的磁盘空间,当使用空间超过90%就通过发mail来发警告

    #!/bin/bash  
    #monitor available disk space  
    #提取本服务器的IP地址信息    
    IP=`ifconfig eth0 | grep "inet addr" | cut -f 2 -d ":" | cut -f 1 -d " "`      
    SPACE=` df -hP | awk '{print int($5)}'`  
    if [ $SPACE -ge 90 ]  
    then  
      echo "$IP 服务器 磁盘空间 使用率已经超过90%,请及时处理。"|mail -s "$IP 服务器硬盘告警,
      公众号:Geek安全"   fty89@163.com  
    fi
    

    监控服务器网卡流量

    #!/bin/bash
    #network
    #Mike.Xu
    while : ; do
    speedtime='date +%m"-"%d" "%k":"%M'
    speedday='date +%m"-"%d'
    speedrx_before='ifconfig eth0|sed -n "8"p|awk '{print $2}'|cut -c7-'
    speedtx_before='ifconfig eth0|sed -n "8"p|awk '{print $6}'|cut -c7-'
    sleep 2
    speedrx_after='ifconfig eth0|sed -n "8"p|awk '{print $2}'|cut -c7-'
    speedtx_after='ifconfig eth0|sed -n "8"p|awk '{print $6}'|cut -c7-'
    speedrx_result=$[(speedrx_after-speedrx_before)/256]
    speedtx_result=$[(speedtx_after-speedtx_before)/256]
    echo"$speedday$speedtime Now_In_Speed: "$speedrx_result"kbps Now_OUt_Speed: "$speedtx_result"kbps"
    sleep 2
    done
    

    检测CPU剩余百分比

    #!/bin/bash
    
    #Inspect CPU
    
    #Sun Jul 31 17:25:41 CST 2016
    
    PATH=/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/home/wl/bin
    export PATH
    
    TERM=linux
    export TERM
    
    CpuResult=$(top -bn 1 | grep "Cpu" | awk '{print $5}' | sed 's/\..*$//g')
    
    if [[ $CpuResult < 20 ]];then
      echo "CPU WARNING : $CpuResult" > /service/script/.cpu_in.txt
      top -bn 1 >> /service/script./cpu_in.txt
      mail -s "Inspcet CPU" wl < /service/script/.cpu_in.txt
    fi
    
    

    检测磁盘剩余空间

    #!/bin/bash
    
    #Insepct Harddisk , If the remaining space is more than 80%, the message is sent to the wl
    
    #Tue Aug  2 09:45:56 CST 2016
    
    PATH=/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/home/wl/bin
    
    export PATH
    
    for RemainingSpace in $(df -h | awk '{print $5}' | grep -v 'Use' | sed -e 's/[%]//g')
    do
      if [[ $RemainingSpace > 80 ]];then
        echo -e "$RemainingSpace"
        echo -e "$(df -h | grep $RemainingSpace)" > /service/script/.HarddiskWarning
        mail -s "disk Warning" wl < /service/script/.HarddiskWarning
      fi
    done
    
    

    判断哪些用户登陆了系统

    #!/bin/bash
    
    declare -i count=0
    
    while true;do
    
            if who |grep -q -E "^wang"
            then
                    echo -e "用户wang 登陆了系统\n 这是第$count 次!威信公众浩:wljsghq"
                    break
            else
                    let count++
            fi
    
            sleep 3
    done
    ~    
    
    示例:找出UID为偶数的所有用户,显示其用户名和ID号;
    
    #!/bin/bash
    while read line; do
        userid=$(echo $line | cut -d: -f3)
        if [ $[$userid%2] -eq 0 ]; then
    echo $line | cut -d: -f1,3
        fi
    done < /etc/passwd
    

    批量扫面存活

    #!/bin/bash
    #By:lyshark
    
    #nmap 192.168.22.0/24>ip
    
    MAC=`cat ip |awk '$1 == "MAC" && $NF == "(VMware)"{print $3}'`
    
    for i in `seq 1 20`
    
    do
    
    temp=`echo ${MAC[@]} |awk '{print $i}'`
    
    IP=`cat /ip |grep  -B5 $temp |grep "Nmap scan"|awk '{print $5}'`
    
        echo $IP |awk '{print $1}'
    done
    

    正则匹配IP

    ^[0-9]{0,2}|^1[0-9]{0,2}|^2[0-5]{0,2}
    
     egrep "(^[0-9]{1,2}|^1[0-9]{0,2}|^2[0-5]{0,2})\.([0-9]{1,2}|1[0-9]{0,2}|2[0-5]{0,2})\.([0-9]{1,2}|1[0-9]{0,2}|2[0-5]{0,2})\.([0-9]{1,2}|1[0-9]{0,2}|2[0-5]{0,2})$"
    
    ([0-9]{1,2}|1[0-9]{0,2}|2[0-5]{0,2})
    ([0-9]{1,2}|1[0-9]{0,2}|2[0-5]{0,2})
    ([0-9]{1,2}|1[0-9]{0,2}|2[0-5]{0,2})
    ([0-9]{1,2}|1[0-9]{0,2}|2[0-5]{0,2})
    
    egrep "((25[0-5]|2[0-4][0-9]|((1[0-9]{2})|([1-9]?[0-9])))\.){3}(25[0-5]|2[0-4][0-9]|((1[0-9]{2})|([1-9]?[0-9])))"
    
    ls |egrep "((25[0-5]|2[0-4][0-9]|((1[0-9]{2})|([1-9]?[0-9])))\.){3}(25[0-5]|2[0-4][0-9]|((1[0-9]{2})|([1-9]?[0-9])$))"
    

    正则匹配邮箱

    egrep "^[0-9a-zA-Z][0-9a-zA-Z_]{1,16}[0-9a-zA-Z]\@[0-9a-zA-Z-]*([0-9a-zA-Z])?\.(com|com.cn|net|org|cn)$" rui
    
    ls |egrep "^(([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-4])$"
    

    相关文章

      网友评论

        本文标题:Shell学习笔记-收藏的脚本

        本文链接:https://www.haomeiwen.com/subject/yoklyrtx.html