阿牛 发表于 2018-8-19 14:02:13

Bash shell脚本练习(一)

  一、此题来源51cto linux论坛版
  

  用户输入A;B;C;D;E;F;G
  输入A的话就查看/etc/passwd最后5个系统用户,只要显示用户名和UID就行了,其他不要
  输入B的话就显示系统开机时间多久了
  输入C的话就判断当前磁盘根目录使用情况是否超过50%,如果超过50%就显示“disk space is used over 50%”;如果没超过50%就显示“disk space is user below 50%”
  输入D的话就显示出系统当前处于LISTEN状态的PID进程程序名称,以“program-name(pid)”这种形式显示。
  输入E的话获取系统的IP和掩码,以"IP/NETMASK"形式显示
  输入F的话添加系统用户,完了后添加该用户密码(记得给以提示操作)
  输入G的话显示系统使用率最多的10条命令,还有使用的次数
  还有一点,执行脚本的时候要说清楚下ABCDEFG各个选项的作用!
  如果输入其他非ABCDEFG选项的错误选项,就显示“your input is wrong”消息
  


[*]# cat test.sh
[*]#!/bin/bash
[*]
[*]read -p "A B C D E F G:" u
[*]
[*]
[*]case $u in
[*]      )
[*]                tail -5 /etc/passwd | awk -F: '{print $1,$3}'
[*]      ;;
[*]      )
[*]                echo "你的系统运行了:"`uptime | awk '{print $3}' | sed 's/\,//'`
[*]      ;;
[*]      )
[*]      User=`df | grep "/$" | awk '{print $5}'| sed 's/%//'`
[*]
[*]      if [ "$User" -gt 50 ]; then
[*]
[*]                echo "disk space is used over 50%"
[*]
[*]      else
[*]
[*]                echo "disk space is user below 50%"
[*]      fi
[*]      ;;
[*]      )
[*]                netstat -tulp | grep "LISTEN" | awk '{print $7}' | awk -F/ '{print $2"("$1")"}'
[*]      ;;
[*]      )
[*]                ip=`ifconfig eth0 | grep "inet addr"| awk '{print $2}' | awk -F: '{print $2}'`
[*]                Mask=`ifconfig eth0 | grep "Mask"| awk '{print $4}' | awk -F: '{print $2}'`
[*]                echo "系统IP:" $ip\/$Mask
[*]      ;;
[*]      )
[*]                read -p "please input you username:" username
[*]                read -p "please input you password:" password
[*]
[*]                useradd $username
[*]                echo "$password" | passwd --stdin $username
[*]                echo "用户建立完成"
[*]      ;;
[*]      )
[*]                cat ~/.bash_history | sort | uniq -c | sort -nk 1 | tail
[*]      ;;
[*]      *)
[*]                echo "you input is wrong"
[*]
[*]esac
  

  二、判断主机类型
  


[*]#!/bin/bash
[*]
[*]ip="192.168.209."
[*]LOG="/tmp/ip.log"
[*]for i in `seq 1 254`
[*]do
[*]
[*]      ping -c 2 "$ip$i">/tmp/log.txt
[*]
[*]      if [ $? -ne 0 ]; then
[*]                continue
[*]      fi
[*]
[*]      okip=`cat /tmp/log.txt | grep ttl |awk -F '[: =]' '{print $4}'|sort|uniq `
[*]      ttl=`cat /tmp/log.txt | grep ttl | awk -F '[: =]' '{print $9 }'|uniq`
[*]      if [ $ttl -eq 64 ]; then
[*]                echo "check $okip is linux"
[*]      elif [ $ttl -eq 128 ]; then
[*]                echo "check $okip is windows"
[*]      else
[*]                echo "other"
[*]      fi
[*]done
  

  判断原理:根据ping返回ttl值,进行判断


页: [1]
查看完整版本: Bash shell脚本练习(一)