shell脚本实践

  1. 编写一个shell脚本,判断192.168.1.0/24络内,在线的ip有哪些,能ping通就代表在线。

    [root@shell scripts]# vim 001-judge_ip.sh
    #!/bin/bash
    
    for ip in $(seq 254)
    do
        ping -c 1 192.168.1.$ip &>/dev/null
        if [ $? = 0 ];then
            echo 192.168.1.$ip is online
        fi
    done
    
  2. 编写一个shell脚本,批量创建5个用户并且创建8位随机密码。

    # 第一种方法
    [root@shell scripts]# vim 002-creat_user.sh
    #!/bin/bash
    
    for u in user{01..05}
    do
        useradd $u
        PWD=`tr -dc '0-z' </dev/urandom | head -c 8`
        echo -e "user:$u\npassword:$PWD" >>/tmp/user.txt
        echo "$u:$PWD" | chpasswd
    done
    # 第二种方法
    [root@shell scripts]# vim 002-creat_user.sh
    #!/bin/bash
    
    for u in oldboy{01..05}
    do
        useradd $u
        for p in `echo $RANDOM | md5sum | cut -c 1-8`
        do
            echo -e "user:$u\npassword:$p" >>/tmp/user.txt
            echo "$u:$p" | chpasswd
        done
    done
    
  3. 编写一个批量分发公钥的脚本。

    # CentOS 7.x版本
    [root@shell scripts]# vim batch.sh
    #!/bin/bash
    
    PWD=接收公钥主机的密码
    
    rm -rf /root/.ssh/id_dsa*
    ssh-keygen -t dsa -f /root/.ssh/id_dsa -P '' -q
    
    for ip in $*
    do
        sshpass -p $PWD ssh-copy-id -i /root/.ssh/id_dsa.pub -o StrictHostKeyChecking=no $ip &>/dev/null
        if [ $? != 0 ];then
            echo -e "\n----- $ip distribution of failure -----\n" 
            continue
        fi
    done
    
  4. 找出目录中大于200M的日志文件并压缩,压缩文件仍保留在原目录中,压缩完成后删除原日志文件。

    [root@shell scripts]# vim find.sh
    #!/bin/bash
    
    for file in `find /data/logs -type f -name '*.log' -size +200M`
    do
        filename=`basename  ${file}`
        dirname=`dirname  ${file}`
        cd ${dirname}
        tar -zcPf ${filename}.tar.gz ${filename} --remove-files
    done
    


写作不易,转载请注明出处,谢谢~~

posted @ 2019-08-28 22:27  merlee  阅读(407)  评论(0编辑  收藏  举报