一些常用的Shell脚本笔记,这是当年在兄弟连学习Linux运维是写过的一些案例,后期在工作中也遇到了一些问题需要使用shell来解决的,这里总结起来方便以后可以直接复用。
轮询检测Apache状态并启用钉钉报警
代码语言:javascript复制#!/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分钟执行一次。
代码语言:javascript复制#!/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
监控主机的磁盘空间,当使用空间超过90%就通过发mail来发警告
代码语言:javascript复制#!/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 服务器硬盘告警" fty89@163.com
fi
实现FTP自动上传
代码语言:javascript复制#! /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 备份数据库目录脚本
代码语言:javascript复制#!/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
在终端中实现打印彩虹
代码语言:javascript复制declare -a ary
for i in `seq 40 49`
do
ary[$i]=" "
echo -en "e[$i;5m ${ary[@]}e[;0m"
done
declare -a ary
for s in `seq 1 10000`
do
for i in `seq 40 49`
do
ary[$i]=" "
echo -en "e[$i;5m ${ary[@]}e[;0m"
done
done
在终端中实现打印菱形
代码语言:javascript复制#!/bin/bash
for (( i = 1; i < 12; i ))
do
if [[ $i -le 6 ]]
then
for ((j = $((12-i)); j > i; j--))
do
echo -n " "
done
for ((m = 1; m <= $((2*i-1)); m ))
do
echo -n "* "
done
echo ""
#*****************************************************************************
elif [[ $i -gt 6 ]]
then
n=$((12-i))
for ((j = $((12-n)); j > n; j--))
do
echo -n " "
done
for ((m = 1; m <= $((2*n-1)); m ))
do
echo -n "* "
done
echo ""
fi
done
expect实现远程登陆自动交互
代码语言:javascript复制#!/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 "yesr";exp_continue }
"password:" { send "$passwdr" }
}
#expect "*from*"
#send "mkdir -p ./tmp/testfiler"
#send "exitr"
#expect "#" #i# 命令运行完, 你要期待一个结果, 结果就是返回shell提示符了(是# 或者$)
http心跳检测
代码语言:javascript复制URL="http://192.168.22.191/index.html"
THHP_CODE=`curl -o /dev/null -s -w "%{http_code}" "${URL}"`
if [ $HTTP_CODE != 200 ]
then
echo -e "apache code:"$HTTP_CODE""
fi
PV过量自动实现防火墙封IP
代码语言:javascript复制#!/bin/bash
log=/tmp/tmp.log
[ -f $log ] || touch $log
function add_iptales()
{
while read line
do
ip=`echo $line |awk '{print $2}'`
count=`echo $line |awk '{print $1}'`
if [ $count -gt 100 ] && [ `iptables -L -n |grep "$ip" |wc -l` -lt 1 ]
then
iptables -I INPUT -s $ip -j DROP
echo -e "$list isdropped">>/tmp/droplist.log
fi
done<$log
}
function main()
{
while true
do
netstat -an|grep "EST" |awk -F '[:] ' '{print $6}'|sort |uniq -c >$log
add_iptales
sleep 180
done
}
main
shell实现自动安装
代码语言:javascript复制#!/bin/bash
function MyInstall
{
if ! rpm -qa |grep -q "^$1"
then
yum install $1
if [ $? -eq 0 ]
then
echo -e "$i install is okn"
else
echo -e "$1 install non"
fi
else
echo -e "yi an zhuang ! n"
fi
}
for ins in mysql php httpd
do
MyInstall $ins
done
shell实现插入排序
代码语言:javascript复制#!/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实现动态进度条
代码语言:javascript复制#!/bin/bash
i=0
bar=''
index=0
arr=( "|" "/" "-" "\" )
while [ $i -le 100 ]
do
let index=index%4
printf "[%-100s][%d%%][e[43;46;1m%ce[0m]r" "$bar" "$i" "${arr[$index]}"
let i
let index
usleep 30000
bar ='#'
clear
done
printf "n"
根据文件内容创建账号
代码语言:javascript复制#!/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
实现红色进度条
代码语言:javascript复制#!/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
监控服务器网卡流量
代码语言:javascript复制#!/bin/bash
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剩余百分比
代码语言:javascript复制#!/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
检测磁盘剩余空间
代码语言:javascript复制#!/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
bash-实现检测apache状态并钉钉报警
代码语言:javascript复制#!/bin/bash
function trans_text(){
text=$1
curl 'https://oapi.dingtalk.com/robot/send?access_token=b4fcf5862088a1bc7f2bf66aea051869e62ff5879fa0e0fddb0db9b1494781c2' -H'Content-Type: application/json' -d'
{
"msgtype": "text",
"text": {
"content": "'"$text"'"
},
}'
}
function desk_check(){
dftype=$1
shell_row=`df |wc -l`
for i in `seq 2 $shell_row`
do
temp=(`df -h |head -n $i |tail -n 1 |awk '{print $5 "t" $6}'`)
disk="`echo ${temp[0]} |cut -d "%" -f 1`"
name="${temp[1]}"
hostname=`hostname`
IP=`ifconfig |grep -v "127.0.0.1" |grep "inet addr:" |sed 's/^.*inet addr://g'|sed 's/ Bcas..*$//g'`
#echo -e "$disk $name"
Dat=`date " %F %T"`
if [ $disk -ge $dftype ]
then
echo "
======================== n
>磁盘分区异常< n
主机名: $hostname n
IP地址: $IP n
分区名: $name n
使用率: $disk %n
发生时间: $Dat n
========================= n"
fi
done
}
function apache_check(){
url=$1
URL="http://$url/"
HTTP_CODE=`curl -o /dev/null -s -w "%{http_code}" "${URL}"`
if [ $HTTP_CODE != 200 ]
then
echo "
======================== n
>Apache服务异常<
主机名: $hostname n
IP地址: $IP n
返回代码: $HTTP_CODE n
发生时间: $Dat n
========================= n"
fi
}
while true
do
desk_check 10
apache_check 127.0.0.1
sleep 10
done
bash实现内存检测
代码语言:javascript复制#!/bin/bash
#Inspect Memory : If the memory is less than 500 , then send mail to wl
PATH=/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/home/wl/bin
export PATH
MEM=$(free -m | grep "Mem" | awk '{print $4}')
if [[ MEM < 500 ]];then
echo -e "Memory Warning : Memory free $MEM" > /service/script/.MemoryWarning
mail -s "Memory Warning" wl < /service/script/.MemoryWarning
fi
剩余inode检测
代码语言:javascript复制#!/bin/bash
#Inspcet Inode : If the free INODE is less than 200, the message is sent to the wl
PATH=/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/home/wl/bin
export PATH
for FreeInode in $(df -i | grep -v "Filesystem" | awk '{print $4}')
do
if [[ $FreeInode < 200 ]];then
echo -e "$(df -i | grep "$FreeInode")" > /service/script/.FreeInode
mail -s "FreeInode Warning" wl < /service/script/.FreeInode
fi
done
判断哪些用户登陆了系统
代码语言:javascript复制#!/bin/bash
declare -i count=0
while true;do
if who |grep -q -E "^wang"
then
echo -e "用户wang 登陆了系统n 这是第$count 次!"
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
批量创建账号
代码语言:javascript复制#!/bin/bash
sum=1
while [ $sum -le 30 ]
do
if [ $sum -le 9 ]
then
user="user_0$sum"
else
user="user_$sum"
fi
useradd $user
echo "123456" |passwd --stdin $user
chage -d 0 $user
let sum=sum 1
done
批量扫描主机存活
代码语言:javascript复制#!/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
代码语言:javascript复制^[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])$))"
正则匹配邮箱
代码语言:javascript复制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])$"
实现布片效果
代码语言:javascript复制#!/bin/bash
function ary_go
{
$1 $2
for (( i=0;i<=$1;i ))
do
for (( s=0;s<=$2;s ))
do
if [ $[$i%2] == 0 ]
then
if [ $[$s%2] == 0 ]
then
echo -en " "
else
echo -en "e[;44m e[;m"
fi
else
if [ $[$s%2] == 0 ]
then
echo -en "e[;42m e[;m"
else
echo -en " "
fi
fi
done
echo
done
}
ary_go 25 50
剔除白名单以外的用户
代码语言:javascript复制#!/bin/bash
w | awk 'NR>=3 {printf $1 "t" $2 "t" $3 "n"}' > /tmp/who.txt
for i in $(awk '{printf $1}' /tmp/bai.txt)
do
k=$(egrep -v "$i" /tmp/who.txt | awk '{printf $2} "n"' | awk '{printf $2 "n"}')
for j in $k
do
pkill -9 -t "$j"
done
done
Shell实现的一个自动化管理工具
代码语言:javascript复制#!/bin/bash
shell_user="root"
shell_pass="1233"
shell_port="22"
shell_list="/root/ip_list"
shell_row=`cat $shell_list |wc -l`
comad[0]=$1
comad[1]=$2
comad[2]=$3
comad[3]=$4
comad[4]=$5
comad[5]=$6
comad[6]=$7
comad[7]=$8
comad[8]=$9
comad[9]=${10}
comad[10]=${11}
comad[11]=${12}
comad[12]=${13}
comad[13]=${14}
comad[14]=${15}
comad[15]=${16}
comad[16]=${17}
comad[17]=${18}
comad[18]=${19}
comad[19]=${20}
comad[20]=${21}
function shell_exp(){
date_start=`date "%T"`
rm -fr ./shell_log
for temp in `seq 1 $shell_row`
do
Ip_Addr=`cat $shell_list |head -n $temp |tail -n 1`
ping -c 1 $Ip_Addr &>/dev/null
if [ $? -eq 0 ]
then
echo -e "e[34;1m====================================================>$Ip_Addr<=======================================================e[;mn"
ssh -p $shell_port $shell_user@$Ip_Addr ${comad[*]}
if [ $? -eq 0 ]
then
echo -e "$Ip_Addrtt$shell_porttt${comad[*]} tt成功n" >>./shell_log
fi
else
echo -e "$Ip_Addrtt$shell_porttt${comad[*]} tt失败n" >>./shell_log
continue
fi
done
date_end=`date "%T"`
clear
echo -e "e[34;1m===========================================================================================================================e[;m"
echo -e "e[34;1m主机IP 端口 命令 状态 e[;mn"
cat ./shell_log
echo -e "e[34;1m===========================================================================================================================e[;mn"
echo -e "e[34;1m 开始时间:$date_start ttt 结束时间:$date_end tttt e[;mn"
echo -e "e[34;1m 执行主机数:$shell_row ttt 成功主机:`cat ./shell_log |grep "成功" |wc -l` ttt 失败主机:`cat ./shell_log |grep "失败" |wc -l`ttte[;mn"
echo -e "e[34;1m 失败主机记录 ↓e[;mn"
cat ./shell_log |grep "失败"
echo -e "e[34;1m===========================================================================================================================e[;mn"
}
function shell_upload(){
date_start=`date "%T"`
rm -fr ./shell_log
for temp in `seq 1 $shell_row`
do
take_ip=`cat $shell_list |head -n $temp |tail -n 1`
Ip_Addr="$take_ip"
ping -c 1 $Ip_Addr &>/dev/null
if [ $? -eq 0 ]
then
scp ${comad[1]} $shell_user@$Ip_Addr:${comad[2]} &>/dev/null
if [ $? -eq 0 ]
then
echo -e "e[34;1m$Ip_Addrtt 传输完成....e[;mn"
echo -e "$Ip_Addrtt$shell_porttt${comad[1]}tt${comad[2]}tttt成功n" >>./shell_log
fi
else
echo -e "e[34;1m$Ip_Addrtt 传输失败....e[;mn"
echo -e "$Ip_Addrtt$shell_porttt${comad[1]}tt${comad[2]}tttt失败n" >>./shell_log
continue
fi
done
date_end=`date "%T"`
clear
echo -e "e[34;1m===========================================================================================================================e[;m"
echo -e "e[34;1m主机IP 端口 传输源 传输到 状态 e[;mn"
cat ./shell_log
echo -e "e[34;1m===========================================================================================================================e[;mn"
echo -e "e[34;1m 开始时间:$date_start ttt 结束时间:$date_end tttt e[;mn"
echo -e "e[34;1m 执行主机数:$shell_row ttt 成功主机:`cat ./shell_log |grep "成功" |wc -l` ttt 失败主机:`cat ./shell_log |grep "失败" |wc -l`ttte[;mn"
echo -e "e[34;1m 失败主机记录 ↓e[;mn"
cat ./shell_log |grep "失败"
echo -e "e[34;1m===========================================================================================================================e[;mn"
}
function shell_meminfo(){
echo -e "e[34;1m===========================================================================================================================e[;m"
echo -e "e[34;1m IP地址ttt总量tt已使用tt剩余tt共享tt缓冲tt缓存ttn e[;m"
for temp in `seq 1 $shell_row`
do
take_ip=`cat $shell_list |head -n $temp |tail -n 1`
Ip_Addr="$take_ip"
echo -ne "e[34;1m $take_iptt e[;m"
# sleep 0.5
ping -c 1 $Ip_Addr &>/dev/null
if [ $? -eq 0 ]
then
ssh $shell_user@$take_ip free -h |grep "Mem:" |awk '{print $2 "tt" $3 "tt" $4 "tt" $5 "tt" $6 "tt" $7}'
else
echo -e "0Mtt0Mtt0Mtt0Mtt0Mtt0M"
fi
done
echo -e "e[34;1m===========================================================================================================================e[;m"
}
#==============================================批量分发SSH密钥函数体-开始=======================================================================
function shell_ssh_keygen(){
/usr/bin/expect << EOF
set timeout 5
spawn ssh-keygen -t rsa
expect {
"*save the key*" {send "n";exp_continue}
"Enter passphrase*" {send "n";exp_continue}
"*passphrase again:" {send "n"}
}
expect eof
EOF
}
function shell_push_sshkey(){
local ssh_user=$1
local ssh_host=$2
local ssh_pass=$3
/usr/bin/expect << EOF
set timeout 10
spawn ssh-copy-id $ssh_user@$ssh_host
expect {
"(yes/no)" {send "yesn"; exp_continue}
"password:" {send "$ssh_passn"}
"id_rsa.pub" {puts "(^_^)n";exit 2n}
}
expect eof
EOF
}
function shell_expect(){
for temp in `seq 1 $shell_row`
do
Ip_Addr=`cat $shell_list |head -n $temp |tail -n 1`
shell_push_sshkey $shell_user $Ip_Addr $shell_pass
done
}
#==============================================批量分发SSH密钥函数体-结束=======================================================================
function shell_add_ip(){
[ -e $shell_list ] || touch $shell_list
echo "${comad[1]}" >>$shell_list
if [ $? -ne 0 ]
then
echo -e "e[34;1m 添加IP:${comad[1]}失败 e[;mnn"
exit 1
fi
}
function shell_show_ip(){
[ -e $shell_list ] || touch $shell_list
echo -e "e[34;1m====================================================================nne[;m"
echo -e "e[34;1m`cat $shell_list` nne[;m"
echo -e "e[34;1m总计:`cat $shell_list |wc -l `ttt 操作列表:$shell_listnne[;m"
echo -e "e[34;1m====================================================================nne[;m"
}
function shell_drop_ip(){
#sed -i '/echo "${comad[1]}"/d' $shell_list
# for i in `seq 1 $shell_row`
# do
# Ip_Addr=`cat $shell_list |head -n $temp |tail -n 1`
# if [ "$Ip_Addr" == "$del_ip" ]
# then
# donei
# cat $shell_list |grep -v ${comad[1]} >/root/ip_list.tmp
# rm -fr /root/ip_list
# mv /root/ip_list.tmp /root/ip_list
rm -fr $shell_list
touch $shell_list
}
function shell_init(){
touch $shell_list
yum install -y expect
[ $? -eq 0 ]
echo -e "e[34;1m 初始化成功... e[m"
}
function shell_help(){
echo -e "e[34;1m====================================================================n"
# echo -e "注:如需要多线程执行,请自行在for语句下加入{} 并写入 wait 即可支持多线程,加快传输速度nn"
# echo -e "ttt[使用时请自行在/root/目录下创建ip_list文件并写入你要控制的主机]nn"
echo -e "t-shell [任意命令] 批量远程执行命令n"
echo -e "t-init 初始化n"
echo -e "t-show 显示控制列表n"
echo -e "t-add 添加一个被管理主机n"
echo -e "t-del 删除一个被管理主机n"
echo -e "t-drop 清空一个主机列表n"
echo -e "t-keys 本地生成密钥对n"
echo -e "t-scpkeys 批量分发密钥对n"
echo -e "t-upload [本地文件] [传输到] 批量传输文件n"
echo -e "t-mem 批量统计主机内存使用n"
echo -e "====================================================================nn"
echo -e " Powered by LySharkn"
echo -e "====================================================================e[;m"
}
case ${comad[0]} in
"")
shell_help
exit 1
;;
"-upload")
shell_upload
exit 1
;;
"-mem")
shell_meminfo
exit 1
;;
"-keys")
shell_ssh_keygen
exit 1
;;
"-scpkeys")
shell_expect
exit 1
;;
"-add")
shell_add_ip
exit 1
;;
"-show")
shell_show_ip
exit 1
;;
"-drop")
shell_drop_ip
exit 1
;;
"-init")
shell_init
exit 1
;;
*) shell_exp
exit 1
;;
esac
LVS实现健康检查脚本
代码语言:javascript复制#!/bin/bash
#=============================================================================
VIP=10.10.10.100 #集群虚拟IP
CPORT=80 #定义集群端口
FAIL_BACK=127.0.0.1 #本机回环地址
RS=("10.10.10.12" "10.10.10.13") #编写集群地址
declare -a RSSTATUS #变量RSSTATUS定义为数组态
RW=("2" "1")
RPORT=80 #定义集群端口
TYPE=g #制定LVS工作模式:g=DR m=NAT
CHKLOOP=3
LOG=/var/log/ipvsmonitor.log
#=============================================================================
addrs() {
ipvsadm -a -t $VIP:$CPORT -r $1:$RPORT -$TYPE -w $2
[ $? -eq 0 ] && return 0 || return 1
}
delrs() {
ipvsadm -d -t $VIP:$CPORT -r $1:$RPORT
[ $? -eq 0 ] && return 0 || return 1
}
checkrs() {
local I=1
while [ $I -le $CHKLOOP ]
do
if curl --connect-timeout 1 http://$1 &> /dev/null
then
return 0
fi
let I
done
return 1
}
initstatus() {
local I
local COUNT=0;
for I in ${RS[*]}
do
if ipvsadm -L -n | grep "$I:$RPORT" && > /dev/null
then
RSSTATUS[$COUNT]=1
else
RSSTATUS[$COUNT]=0
fi
let COUNT
done
}
#=============================================================================
initstatus
while :; do
let COUNT=0
for I in ${RS[*]}
do
if checkrs $I
then
if [ ${RSSTATUS[$COUNT]} -eq 0 ]
then
addrs $I ${RW[$COUNT]}
[ $? -eq 0 ] && RSSTATUS[$COUNT]=1 && echo "`date '%F %H:%M:%S'`, $I is back." >> $LOG
fi
else
if [ ${RSSTATUS[$COUNT]} -eq 1 ]
then
delrs $I
[ $? -eq 0 ] && RSSTATUS[$COUNT]=0 && echo "`date '%F %H:%M:%S'`, $I is gone." >> $LOG
fi
fi
let COUNT
done
sleep 5
done
在Bash环境下实现密钥对分发功能,首先创建文件,然后直接分发。
代码语言:javascript复制#!/usr/bin/expect
set timeout 10
set hostname [lindex $argv 0]
set username [lindex $argv 1]
set password [lindex $argv 2]
spawn ssh-copy-id $username@$hostname
expect {
"Are you sure you want to continue connecting (yes/no)?" {
send "yesr"
expect "*password:"
send "$passwordr"
}
"*password:" {
send "$passwordr"
}
"Now try logging into the machine" {
}
}
expect eof
在bash中,用expect -c 把expect语句包起来,将expect -c 中的双引号加上反斜杠
代码语言:javascript复制#!/bin/bash
USER=root
PASSWD=1233
# yum install -y expect
for HOST in 192.168.1.{1..10}
do
echo "------------------>" $HOST "-----------------------------"
/usr/bin/expect -c "
spawn ssh-copy-id $USER@$HOST;
expect {
"Are you sure you want to continue connecting (yes/no)?" {
send "yesr"
expect "*password:"
send "$PASSWDr"
}
"*password:" {
send "$PASSWDr"
}
"Now try logging into the machine" {
}
}
expect eof
"
done