自动登录linux server(shell版本)
不熟悉python的同学可以用shell脚本来登录远程服务器,这样子就不用再本地保存这么多putty session,在一台linux跳板机上就能登录所有的其他机器。
为了使用更加简单方便,还可以设置一下alias,可以快速的调用login脚本:
[demo@demo-vm scripts]$ cat ~/.bashrc
alias st='/home/demo/scripts/logins.sh'
-
logins.sh
#! /usr/bin/bash
#Author Eric Yang
#Date 2018-6-10
date=$(date +'[%F %T]')
color_end='\e[0m'
color_red='\e[1;31m'
color_green='\e[1;32m'
color_yellow='\e[1;33m'
color_skyblue='\e[1;36m'
autoScript=~/scripts/login.exp
#add the server info into below 4 array manually
function initPara()
{
if [ "$1" = "0" ]
then
echo -e "You are going to login ${color_red}QA environment${color_end}."
hostname=(QA_demo1 QA_demo2 )
ipaddr=(10.10.10.1 10.10.10.2)
account=(root root)
passwd=(demo demo)
elif [ "$1" = "1" ]
then
echo -e "You are going to login ${color_red}dev environment${color_end}."
hostname=(DEV_demo1 DEV_demo2 )
ipaddr=(10.10.10.3 10.10.10.4)
account=(root root)
passwd=(demo demo)
else
echo "Error: Your Input is invalid. Exit the programe"
exit 10
fi
}
function promotionMessage()
{
length=${#hostname[@]}
for((i=0;i<$length;i++))
do
echo -e "$color_red$i: ${hostname[$i]}$color_end ${ipaddr[$i]}"
done
}
echo -e "Do you want to login?"
echo -e "0: QA Env; 1: DEV Env;"
read -t 10 -p "Plese input: " envs
initPara $envs
promotionMessage
read -t 10 -p "please input your selection: " serverOption
case "$serverOption" in
[0-9]|1[0-9]|2[0-9])
echo -e "$date: Welcome to environemnt ${color_red}${hostname[$serverOption]}${color_end}"
$autoScript ${ipaddr[$serverOption]} ${account[$serverOption]} ${passwd[$serverOption]}
;;
*)
echo -e "${color_red}Error:${color_end} your input is invalid, exit the program\n"
exit 1
;;
esac
-
expect脚本
#!/usr/bin/expect -f
# set Variables
set ipaddr [lrange $argv 0 0]
set account [lrange $argv 1 1]
set password [lrange $argv 2 2]
set timeout 2
spawn ssh -q $account@$ipaddr
#match_max 100000
# Look for passwod prompt
expect {
"Are you sure you want to continue connecting (yes/no)?" {
send "yes\r"
exp_continue
}
"*?assword:*" {
send "$password\r"
exp_continue
}
eof
{
send_user "eof\n"
}
}
interact