Linux下在脚本里直接使用账号和密码自动化登录系统

182 次查看 0 条评论

本方法应仅应用于某些不能部署ssh密钥验证的场景(客户服务器)使用,其他场景强烈建议部署密钥验证方式免密码登录。

1、首先安装sshpass工具软件

yum install gcc
wget http://downloads.sourceforge.net/project/sshpass/sshpass/1.06/sshpass-1.06.tar.gz
tar -zxvf sshpass-1.06.tar.gz
cd sshpass-1.06
./configure --prefix=/usr/local/sshpass
make install
cp /usr/local/sshpass/bin/sshpass /usr/bin/

sshpass-1.06.tar.gz

下载后记得MD5安全校验:f59695e3b9761fb51be7d795819421f9

2、自动化登录命令

sshpass -p "${password}" ssh root@${ip}
sshpass -p "123456" ssh root@192.168.1.1

3、批量服务器选择登录脚本

#/bin/bash
#created by Jack 2019-07-29 649781645@qq.com
hosts[1]="172.18.248.80 vm1 password1"
hosts[2]="172.18.248.81 vm2 password2"
hosts[3]="172.18.248.82 vm3 password3"
hosts[4]="172.18.248.83 vm4 password4"
hosts[5]="172.18.248.84 vm5 password5"
length=${#hosts[@]}
echo "---------------------------------"
printf "%5s %-15s %-32s \n" "Index" "IP Address" "HostName"
echo "---------------------------------"
for ((i=1;i<=${#hosts[@]};i++))
do
    host=(${hosts[i]})
    printf "%5s %-15s %-32s \n" "${i}:" "${host[0]}" "${host[1]}"
done
echo "---------------------------------"
read -p "Enter index number to login the server. Please: " index
if [ ${index} -ge 1 ] && [ ${index} -le ${length} ]
then
    host=(${hosts[${index}]})
    ip=${host[0]}
    password=${host[2]}
    clear
    echo "Trying to log in to the server ${ip} ..."
    sshpass -p "${password}" ssh root@${ip}
else
    clear
    echo "Error message: Input errors, please re-enter."
    sh $0
fi

脚本效果图:

99220-2fqpb0pcyqa.png

通过键入对应服务器索引编号,便可以直接登录服务器(适当修改脚本中服务器IP、账号、密码信息)。

Linux SSH

暂无评论,快来抢沙发。