上次写了个互信脚本,有不下10个小伙伴在后台询问是否可以做到双向互信。
波哥想了一下确实双向互信这个场景是存在的,也是普遍的。那么就顺手优化了一下这个脚本。
增加是否双向互信的参数DOUBLE_AUTH=1
默认是单向互信。
增加成功失败的统计参数。
增加互信登录超时时间的参数。
脚本如下:
#!/bin/bash # 获取IP列表和用户名密码 SERVERS=("192.168.1.1" "192.168.1.2" "192.168.1.3") USERNAME="username" PASSWORD="password" # 默认单向互信,如果DOUBLE_AUTH为1则为双向互信 DOUBLE_AUTH=1 # 互信超时时间为30秒 TIMEOUT=30 # 记录成功和失败的IP地址 SUCCESS_IP=() FAIL_IP=() # 循环遍历IP列表 for SERVER in ${SERVERS[@]}; do # 生成本地ssh key ssh-keygen -t rsa -N "" -f ~/.ssh/id_rsa > /dev/null # 复制本地公钥到远程服务器 sshpass -p "$PASSWORD" ssh-copy-id -o ConnectTimeout=$TIMEOUT $USERNAME@$SERVER > /dev/null # 双向互信,需要将远程服务器的公钥复制到本地 if [ $DOUBLE_AUTH -eq 2 ]; then sshpass -p "$PASSWORD" ssh -o ConnectTimeout=$TIMEOUT $USERNAME@$SERVER "ssh-keygen -t rsa -N \"\" -f ~/.ssh/id_rsa > /dev/null && echo 'Hostkey has been created.'" sshpass -p "$PASSWORD" ssh -o ConnectTimeout=$TIMEOUT $USERNAME@$SERVER "cat ~/.ssh/id_rsa.pub" | sshpass -p "$PASSWORD" ssh-copy-id -o ConnectTimeout=$TIMEOUT $USERNAME@$SERVER > /dev/null fi # 检查互信是否成功 if [ $? -eq 0 ]; then SUCCESS_IP+=($SERVER) else FAIL_IP+=($SERVER) fi done # 记录成功和失败的IP地址到日志文件 echo "$(date '+%Y-%m-%d %H:%M:%S') [INFO] Successfully established trust with the following servers: ${SUCCESS_IP[*]}" >> trust.log echo "$(date '+%Y-%m-%d %H:%M:%S') [INFO] Failed to establish trust with the following servers: ${FAIL_IP[*]}" >> trust.log echo "$(date '+%Y-%m-%d %H:%M:%S') [INFO] Total success: ${#SUCCESS_IP[@]}, total fail: ${#FAIL_IP[@]}" >> trust.log
觉的不错,别忘了帮波哥三连哦!