Linux shell 经验手册__002__经典代码片段

来源:互联网 发布:淘宝店铺售假48分重开 编辑:程序博客网 时间:2024/05/29 19:07

1 判断是否为root用户

ROOT_UID=0                    #$UID为0的时候,用户才具有root用户权限;                E_NOTROOT=67                #非root用户if [ "$UID" -ne "$ROOT_UID" ]   #$UID是环境变量then    echo "Must be root to run this script."    exit $E_NOTROOTfi

2 测试是否有命令行参数

if [ -n "$1" ]then    lines=$1else    echo "Usage: `basename $0` xxxx"    exit $E_NOARGS      # 65 if

3 测试脚本参数数量是否正确

E_WRONG_ARGS=65script_parameters="-a -h -m -z"# -a = all, -h = help ......if [ $# -ne $Number_of_expected_args ]then    echo "Usage: `basename $0` $script_parameters"      # basename 可以提取出文件名,去除目录项    exit $E_WRONG_ARGSfi

4 expect 经典示例

  #!/usr/bin/expect   set timeout 30   spawn ssh -l username 192.168.1.1   expect "password:"   send "ispass/r"   interact 

5 shell中数值运算示例

declare -i num=$1declare -i var=0echo "arg is $num"while [ $num -gt $var ]; do        snmpgetnext -v 2c -c public localhost .1.3.6.1.4.1.193.113.1.7.1.1.2        num=$(($num-1))        echo "num is $num"done

示例2

declare -i count1 count2 indexcount1=0count2=0index=0echo "program start ..."echo "//////////////////////////////////////////////////"while truedo        count1=`date +%M`#       echo "---------------$count1, $count2"        if [ "$count1" -ne "$count2" ];then                index=index+1                count2=count1                echo "-------------------------------- $index"        fi        date | cut -d " " -f 4        dig @10.170.15.194 host.iptelco.com >/dev/null 2>&1        dig @10.170.15.194 hosat.iptesssslco.com >/dev/null 2>&1doneexit 0

示例3

i=0while [ $i -lt $1 ]do#kill -11 `pgrep ttselect`snmpwalk -v2c 10.170.15.146 -t 30 ipworksEnumMessageCounters &i=$[$i + 1] # !!!!doneecho "done"

6 判断特定进程是否存在

#!/bin/shps -fe|grep processString |grep -v grepif [ $? -ne 0 ] #******thenecho "start process....."elseecho "runing....."fi

7 查看主机网卡流量

while : ; dotime='date +%m"-"%d" "%k":"%M'day='date +%m"-"%d'rx_before='ifconfig eth0|sed -n "8"p|awk '{print $2}'|cut -c7-'tx_before='ifconfig eth0|sed -n "8"p|awk '{print $6}'|cut -c7-'sleep 2rx_after='ifconfig eth0|sed -n "8"p|awk '{print $2}'|cut -c7-'tx_after='ifconfig eth0|sed -n "8"p|awk '{print $6}'|cut -c7-'rx_result=$[(rx_after-rx_before)/256]tx_result=$[(tx_after-tx_before)/256]echo "$time Now_In_Speed: "$rx_result"kbps Now_OUt_Speed: "$tx_result"kbps"sleep 2done

8 系统状态监控

IP=192.168.1.227top -n 2| grep "Cpu" >>./temp/cpu.txtfree -m | grep "Mem" >> ./temp/mem.txtdf -k | grep "sda1" >> ./temp/drive_sda1.txt#df -k | grep sda2 >> ./temp/drive_sda2.txtdf -k | grep "/mnt/storage_0" >> ./temp/mnt_storage_0.txtdf -k | grep "/mnt/storage_pic" >> ./temp/mnt_storage_pic.txttime=`date +%m"."%d" "%k":"%M`connect=`netstat -na | grep "219.238.148.30:80" | wc -l`echo "$time $connect" >> ./temp/connect_count.txt

9 EOF使用示例

#!/bin/bashsu - test <<EOFpwd;exit;EOF
原创粉丝点击