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_NOTROOT
fi
2 测试是否有命令行参数
if [ -n "$1" ]
then
lines=$1
else
echo "Usage: `basename $0` xxxx"
exit $E_NOARGS # 65
if
3 测试脚本参数数量是否正确
E_WRONG_ARGS=65
script_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_ARGS
fi
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=$1
declare -i var=0
echo "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 index
count1=0
count2=0
index=0
echo "program start ..."
echo "//"
while true
do
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>&1
done
exit 0
示例3
i=0
while [ $i -lt $1 ]
do
#kill -11 `pgrep ttselect`
snmpwalk -v2c 10.170.15.146 -t 30 ipworksEnumMessageCounters &
i=$[$i + 1] # !!!!
done
echo "done"
6 判断特定进程是否存在
#!/bin/sh
ps -fe|grep processString |grep -v grep
if [ $? -ne 0 ] #******
then
echo "start process....."
else
echo "runing....."
fi
7 查看主机网卡流量
while : ; do
time='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 2
rx_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 2
done
8 系统状态监控
IP=192.168.1.227
top -n 2| grep "Cpu" >>./temp/cpu.txt
free -m | grep "Mem" >> ./temp/mem.txt
df -k | grep "sda1" >> ./temp/drive_sda1.txt
#df -k | grep sda2 >> ./temp/drive_sda2.txt
df -k | grep "/mnt/storage_0" >> ./temp/mnt_storage_0.txt
df -k | grep "/mnt/storage_pic" >> ./temp/mnt_storage_pic.txt
time=`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/bash
su - test <<EOF
pwd;
exit;
EOF