7

一个 ssh 设置免密登陆脚本

 1 year ago
source link: https://blog.kelu.org/tech/2022/09/24/ssh-login-with-keys-script.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

一个 ssh 设置免密登陆脚本

2022-09-24     tech linux shell
linux.jpg

近期应用运维的工作比较多,写了两个脚本。这一篇记录设置多台机器免密登录的。主要知识点如下:

  1. ssh-keygen 用于生成 rsa 公钥密钥。
  2. IFS 是字符串切割为数组的分隔符。
  3. 预先设置 /etc/ssh/sshd_config 里的免密登录。
  4. ssh-copy-id 用于拷贝公钥到目的服务器,授权免密登录。

脚本如下,修改前4个变量即可:

  • TARGET_IPS,填写IP和别称,可以 ssh 别称 免密登录到目的服务器。
  • IS_FULL_MESH,是否所有节点都能免密登录,还是只允许当前节点免密登录。
  • TARGET_USER_NAME,免密登录的用户名
  • RSA_NAME,密钥的名字
#!/bin/bash

#远程主机列表
TARGET_IPS="1.2.3.8:app1,1.2.3.9:app2,1.2.3.10:app3,1.2.3.11:app4,1.2.3.12:gateway1,1.2.3.13:gateway2,1.2.3.14:mmc,1.2.3.15:mid1,1.2.3.16:mid2,1.2.3.17:mid3,1.2.3.18:mid4"
#是否所有主机互通 0/1
IS_FULL_MESH=0
#远程主机用户
TARGET_USER_NAME="kelu"
#秘钥名
RSA_NAME="[email protected]"

mkdir -p $HOME/.ssh
touch $HOME/.ssh/config
ssh-keygen -t rsa -P '' -f "$HOME/.ssh/$RSA_NAME"

###### 创建config文件
IFS=","
arrayIP=($TARGET_IPS)
for ipInfo in ${arrayIP[@]}
do
	IFS=":"
	arrayIPInfo=($ipInfo)
	IP=${arrayIPInfo[0]}
	IPTAG=${arrayIPInfo[1]}
	echo -e "主机名:\t${IPTAG}"
cat >> $HOME/.ssh/config << EOF
Host   $IPTAG
  HostName   $IP
  Port       22
  User       $TARGET_USER_NAME
  IdentityFile    $HOME/.ssh/$RSA_NAME
EOF
done

chmod 644 $HOME/.ssh/config


####### 拷贝公钥
IFS=","
arrayIP=($TARGET_IPS)
for ipInfo in ${arrayIP[@]}
do
	IFS=":"
	arrayIPInfo=($ipInfo)
	IP=${arrayIPInfo[0]}
	IPTAG=${arrayIPInfo[1]}
	echo -e ">>>>>>>>>>>>>>>>>>主机IP:${IP}"
	ssh-copy-id -i "$HOME/.ssh/$RSA_NAME.pub" $TARGET_USER_NAME@$IP

        if [ "$IS_FULL_MESH" -eq 1 ];then
 	  scp $HOME/.ssh/config ${IPTAG}:/home/${TARGET_USER_NAME}/.ssh
 	  scp $HOME/.ssh/$RSA_NAME ${IPTAG}:/home/${TARGET_USER_NAME}/.ssh
	fi
done


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK