Skip to content

Instantly share code, notes, and snippets.

@etins
Last active July 21, 2017 02:41
Show Gist options
  • Save etins/4286cda07d5afa6899cbd9cb7ec60270 to your computer and use it in GitHub Desktop.
Save etins/4286cda07d5afa6899cbd9cb7ec60270 to your computer and use it in GitHub Desktop.
ssh连接到服务器。通过写配置文件的方式简化了输入服务器密码或者通过密钥连接。
#!/bin/bash
#默认服务器配置项
# "服务器名称 端口号 IP地址 登录用户名 登录密码 密钥"
CONFIGS=(
"微信测试服务器 22 47.93.110.22 root password"
"后台测试服务器 22 121.200.73.103 root null ~/.ssh/id_rsa_121"
)
#读取自定义服务器配置文件(server_config)列表,合并服务器配置列表
if [ -f server_config ]; then
while read line
do
CONFIGS+=("$line")
done < server_config
fi
#服务器配置数
CONFIG_LENGTH=${#CONFIGS[*]} #配置站点个数
if [[ $CONFIG_LENGTH -le 0 ]] ;
then
echo "未检测到服务器配置项!"
echo "请在脚本CONFIGS变量中配置或单独创建一个server_config文件并配置"
exit ;
fi
#服务器配置菜单
#这就是一个for循环,循环出configs数组里的数据
function ConfigList(){
for ((i=0;i<${CONFIG_LENGTH};i++));
do
CONFIG=(${CONFIGS[$i]}) #将一维sites字符串赋值到数组
serverNum=$(($i+1))
echo "---(${serverNum})--${CONFIG[0]}(${CONFIG[2]})---"
done
}
#登录菜单
function LoginMenu(){
if [ ! -n $1 ]; then
AutoLogin $1
else
echo "-------请输入登录的服务器序号---------"
ConfigList
echo "请输入您选择登录的服务器序号: "
fi
}
#选择登录的服务器
function ChooseServer(){
read serverNum
if [[ $serverNum -gt $CONFIG_LENGTH ]] ;
then
echo "输入的序号不正确,请重新输入:"
ChooseServer ;
return ;
fi
if [[ $serverNum -lt 1 ]] ;
then
echo "输入的序号不正确,请重新输入:"
ChooseServer ;
return ;
fi
AutoLogin $serverNum;
}
#自动登录
function AutoLogin(){
num=$(($1-1))
CONFIG=(${CONFIGS[$num]})
echo "正在登录【${CONFIG[0]}】"
len=${#CONFIG[*]}
if [ $len == 5 ]
then
expect -c "
spawn ssh -p ${CONFIG[1]} ${CONFIG[3]}@${CONFIG[2]}
expect {
\"*assword\" {set timeout 6000; send \"${CONFIG[4]}\n\"; exp_continue ; sleep 3; }
\"yes/no\" {send \"yes\n\"; exp_continue;}
\"Last*\" { send_user \"\n成功登录【${CONFIG[0]}】\n\";}
}
interact"
else
expect -c "
spawn ssh -p ${CONFIG[1]} -i ${CONFIG[5]} ${CONFIG[3]}@${CONFIG[2]}
expect {
\"Last*\" { send_user \"\n成功登录【${CONFIG[0]}】\n\";}
}
interact"
fi
echo "您已退出【${CONFIG[0]}】"
}
# 程序入口
if [ 1 == $# ]; then
if [ 'list' == $1 ]; then
ConfigList
else
AutoLogin $1
fi
else
LoginMenu
ChooseServer
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment