本文主要是介绍Shell脚本实现自动登录服务器,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.登录脚本
login_server.sh
#!/bin/bash# ReferenceLink:https://yq.aliyun.com/articles/516347#show all host infos of serverList.txtif [[ -f ./serverList.txt ]]
thenhostNum=`cat ./serverList.txt | wc -l`
elseecho "No .serverList.txt in ./ dir, please create it and add server infos."exit
fi
while [ True ]
doecho -e "+++++++++++ Host List ++++++++++++++++"awk -F' ' '{printf("%3d -> %s@%s\n", NR,$1,$2)}' ./serverList.txtecho -e "++++++++++++++++++++++++++++++++++++++"echo -e "Enter hostID at first column."echo -e "Enter q or Q to quit."read hostIDif [[ "$hostID" == 'q' ]] || [[ "$hostID" == 'Q' ]]thenexitelif [[ $hostID -lt 1 ]] || [[ $hostID -gt $hostNum ]]thenecho "Wrong hostID is selected, Only $hostNum hosts are listed, please check."continueelsebreakfi
done
user=""
host=""
passwd=""
eval $(awk -v hostID=$hostID -F' ' '{if (NR==hostID) {printf("user=%s;host=%s;passwd=%s;",$1,$2,$3);}}' ./serverList.txt)
#echo $user, $host, $passwd
echo "login in $user@$host"
expect -c "
set timeout 30spawn ssh $user@$hostexpect {\"*yes/no\" { send \"yes\r\"; exp_continue }\"*?assword:\" { send \"$passwd\r\" }}interact
"
2.服务器列表
serverlist.txt
第一列:系统用户名称;
第二列:服务器ip地址;
第三列:服务器密码。
test1 192.168.1.222 123456
bt 192.168.1.101 123456
st 192.168.1.103 123456
这篇关于Shell脚本实现自动登录服务器的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!