Skip to content

Instantly share code, notes, and snippets.

@xurenlu
Created April 2, 2010 05:15
Show Gist options
  • Save xurenlu/352784 to your computer and use it in GitHub Desktop.
Save xurenlu/352784 to your computer and use it in GitHub Desktop.
#! /bin/bash
#设置console的颜色
TPUT=/usr/bin/tput
RED=`$TPUT setaf 1`
GREEN=`$TPUT setaf 2`
YELLOW=`$TPUT setaf 3`
NORM=`$TPUT op`
HOSTFILE=~/.sshhosts
#输出红色文字,错误提示用
errormsg(){
echo ${RED}$@${NORM}
}
#输出绝色文字,输命令用
greenmsg(){
echo ${GREEN}$@${NORM}
}
#ssh到一台机器;
#密码是用的sshpass 自动输出;
#而SECRET环境变量,是另外设置的;
sshit(){
#proxychains sshpass -p $SECRET ssh $1
sshpass -p $SECRET ssh $1
}
#帮助;
help(){
echo "usage:" $0 " -add www.example.com "
echo "usage:" $0 " -cat (list all hosts)"
}
#加一台机器到sshhost文件中;
sshcat() {
cat $HOSTFILE
}
sshadd(){
if [ -z $1 ];then
help
exit
fi
hosts=`cat $HOSTFILE`
for host in $hosts;
do
if [ $host == $1 ];then
errormsg "$host already exists in $HOSTFILE"
exit
fi
done
echo $1 >> $HOSTFILE
}
#从一个数组中挑中一个主机;
selectarray(){
array=$@
echo "select a host:"
if [ -z $GLOBAL_IDX ];then
read idx
else
idx=$GLOBAL_IDX
fi
if [ -z $idx ];then
echo "you must type a number to choose a host"
exit
fi
item=0
for host in ${array[*]};
do
item=$[$item+1]
if [ $item == $idx ];then
echo "you selected item:" $item $host
sshit $host
fi
done
}
if [ ! -f ${HOSTFILE} ] ;then
errormsg "hosts file $HOSTFILE not exists;"
echo "use commmand:"
greenmsg $0 " -add some.host.com "
echo "to add hosts"
exit
fi
A=`cat ${HOSTFILE}`
wanted=$1
GLOBAL_IDX=
if [ "$1" == "" ];then
for host in $A
do
j=$[$j+1]
echo $j : $host
done
if [ -z $j ];then
echo "the hosts file:$HOSTFILE not exists or empty."
exit
fi
selectarray $A
else
x=$1
if [ `echo $x|grep -E ^[0-9]+$|wc -l` == "1" ];then
GLOBAL_IDX=$x
selectarray $A
#参数是数字
else
#参数是字符串;
declare -a target
k=0
#target[0]="localhost"
if [ $x == "-add" ];then
sshadd $2
exit
fi
if [ $x == "-cat" ];then
sshcat $2
exit
fi
#找出所有符合正则的hosts;
for host in ${A};
do
if [ `echo $host|grep $x|wc -l` == "1" ];then
k=$[$k+1]
target[$k]=$host
#echo $k $host
fi
done
#只有一条符合时,自动登录;
if [ $k == "1" ];then
sshit ${target[$k]}
exit
fi
#列出符合正则的的所有hosts,待用户选取;
ab=0
for t in ${target[*]};
do
ab=$[$ab+1]
echo $ab $t
done
#符合用户查询正则的主机没有,提示用户;
if [ $ab == "0" ];then
echo "the host: ${RED}" $wanted "${NORM} not exists"
exit
else
selectarray ${target[*]}
fi
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment