通过shell脚本配置免密登陆,分为两个脚本,一个是配置文件config.env,一个是正式脚本sshkey.sh。
# config.env
export HOST_USER=(root) export PASSWD=(a) export SSH_HOST=(192.168.165.15 192.168.165.16 192.168.165.165)
以上congfig.env文件中,SSH_HOST参数可配置多个IP,可配置不同的用户
sshkey.sh脚本内容大致如下:
- 在本地用rsa加密方式生成对应的密钥,并将公钥写入到authorized_keys文件中;
- 遍历多台远程服务器,登陆远程服务器生成密钥,并将公钥文件考本到本机,写入本机的authorized_Keys文件中;
- 遍历多台远程服务器,将本地的authorized_Keys文件分别分发到各台服务器上。
#!/bin/bash # sshkey.sh source config.env createLocalKey () { /usr/bin/expect <<_oo_ spawn ssh-keygen -t rsa -b 2048 -N "" -f $HOME/.ssh/id_rsa expect "Overwrite" send "y\r" expect eof _oo_ cat $HOME/.ssh/id_rsa.pub >> $HOME/.ssh/authorized_keys } createRemoteKey () { /usr/bin/expect <<_oo_ spawn ssh $HOST_USER@$ip expect { "yes/no" { send "yes\r";exp_continue } "*assword:" { send "$PASSWD\r" } } sleep 1 send "ssh-keygen -t rsa -b 2048 -N '' -f $HOME/.ssh/id_rsa\r" expect { "(y/n)" { send "y\r" } } sleep 1 send "exit\r" expect eof _oo_ /usr/bin/expect <<_oo_ spawn scp $HOST_USER@$ip:$HOME/.ssh/id_rsa.pub /tmp/id_rsa$ip.pub expect { "yes/no" { send "yes\r";exp_continue } "*assword:" { send "$PASSWD\r" } } expect eof _oo_ cat /tmp/id_rsa$ip.pub >> $HOME/.ssh/authorized_keys rm -rf /tmp/id_rsa$ip.pub } copyToRemote () { /usr/bin/expect <<_oo_ spawn scp $HOME/.ssh/authorized_keys $HOST_USER@$ip:$HOME/.ssh/authorized_keys expect { "yes/no" { send "yes\r";exp_continue } "*assword:" { send "$PASSWD\r" } } expect eof _oo_ } pullPubKey () { for ip in ${MHA_HOST[@]};do if [ $ip == `ifconfig eth0|grep -oP '(?<=inet addr:)\S+'` ];then echo "It's local host" else createRemoteKey fi done } pushAuthorizedKeys () { for ip in ${MHA_HOST[@]};do if [ $ip == `ifconfig eth0|grep -oP '(?<=inet addr:)\S+'` ];then echo "It's local host" else copyToRemote fi done } taskMain () { createLocalKey pullPubKey pushAuthorizedKeys } red_echo () { echo -e "\033[031;1m$@\033[0m"; } green_echo () { echo -e "\033[032;1m$@\033[0m"; } taskMain; rc=$? if [ $rc -ne 0 ] ;then echo "$(red_echo Config ssh without password failed!)" else echo "$(green_echo Config ssh without password success!)" fi exit $rc
如有更好的解决方案,望留言指出,谢谢
标签:
shell
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· Windows编程----内核对象竟然如此简单?
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
2017-07-03 PING[ARC2]: Heartbeat failed to connect to standby 'gqtzdb_dg'. Error is 16047