Original link: https://blog.kelu.org/tech/2022/09/24/ssh-login-with-keys-script.html
Recently, there has been a lot of work in application operation and maintenance, and two scripts have been written. This article records that multiple machines are set up for password-free login. The main points of knowledge are as follows:
-
ssh-keygen
is used to generate rsa public key keys. -
IFS
is the delimiter used to cut strings into arrays. - Pre-set password-free login in
/etc/ssh/sshd_config
. -
ssh-copy-id
is used to copy the public key to the destination server to authorize password-free login.
The script is as follows, modify the first 4 variables:
- TARGET_IPS, fill in IP and nickname, you can
ssh 别称
to log in to the destination server without password. - IS_FULL_MESH, whether all nodes can log in without password, or only allow the current node to log in without password.
- TARGET_USER_NAME, username for password-free login
- RSA_NAME, the name of the key
#!/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
This article is reprinted from: https://blog.kelu.org/tech/2022/09/24/ssh-login-with-keys-script.html
This site is for inclusion only, and the copyright belongs to the original author.