[自动化]ssh自动化免密访问配置
ssh简介#
SSH(Secure Shell)是一种通信加密协议,加密算法包括:RSA、DSA等
- RSA:非对称加密算法,其安全性基于极其困难的大整数的分解(两个素数的乘积);
- DSA:也是非对称加密算法,其安全性基于整数有限域离散对数难题;
ssh免密登录原理#
- 客户端发出认证请求;
- 服务器端使用客户端发送的公钥对一个随机的256位的字符串进行加密,并发送给 客户端;
- 客户端使用私钥对字符串进行解密,并生成一个MD5值发送给服务器端;
- 服务器端根据原始随机字符串生成MD5值进行匹配, 确认客户端身份;
- 至此, 双方互相确认对方身份并建立加密信道, 可以正式进行安全通信。
脚本功能:该脚本实现执行脚本的主机
与其它主机免密登陆。
配置脚本#
vim /root/password_free_conf.sh
#!/bin/bash
# check args count
if test $# -ne 3; then
echo -e "\nUsage: sh $0 < hosts file path> < username > < password >\n"
exit 1
fi
# check hosts file
hosts_file=$1
if ! test -e $hosts_file; then
echo "[ERROR]: Can't find hosts file"
exit 1
fi
username=$2
password=$3
# check sshkey file
sshkey_file=~/.ssh/id_rsa.pub
if ! test -e $sshkey_file; then
expect -c "
spawn ssh-keygen -t rsa
expect \"Enter*\" { send \"\n\"; exp_continue; }
"
fi
# get hosts list
hosts=$(cat $1)
echo "======================================================================="
echo "hosts: "
echo "$hosts"
echo "======================================================================="
function ssh_key_copy(){
# delete history
sed "/$1/d" -i ~/.ssh/known_hosts
# start copy
expect -c "
set timeout 100
spawn ssh-copy-id $username@$1
expect {
\"yes/no\" { send \"yes\n\"; exp_continue; }
\"*assword\" { send \"$password\n\"; }
\"already exist on the remote system\" { exit 1; }
}
expect eof
"
}
# auto sshkey pair
for host in $hosts; do
echo "======================================================================="
# check network
ping -i 0.2 -c 3 -W 1 $host >& /dev/null
if test $? -ne 0; then
echo "[ERROR]: Can't connect $host"
exit 1
fi
cat /etc/hosts | grep -v '^#' | grep $host >& /dev/null
if test $? -eq 0; then
hostaddr=$(cat /etc/hosts | grep -v '^#' | grep $host | awk '{print $1}')
hostname=$(cat /etc/hosts | grep -v '^#' | grep $host | awk '{print $2}')
ssh_key_copy $hostaddr
ssh_key_copy $hostname
else
ssh_key_copy $host
fi
echo ""
done
hosts文件#
vim /root/hosts.text
192.168.1.1
192.168.1.2
192.168.1.3
192.168.1.4
192.168.1.5
192.168.1.6
执行配置#
sh $0 < hosts file path> < username > < password >
for example:
sh /root/password_free_conf.sh /root/hosts.text root 123456
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通