Through the shell script to configure the password-free login, divided into two scripts, one is the configuration file config.env, one is the formal script sshkey.sh.
# config.env
Export host_user=(root) export PASSWD=(a) export ssh_host= (192.168. 165.15192.168. 165.16 192.168. 165.165)
In the congfig.env file above, the Ssh_host parameter can be configured with multiple IPs to configure different users
The sshkey.sh script content is as follows:
- The corresponding key is generated locally using RSA encryption, and the public key is written to the Authorized_keys file;
- Traverse multiple remote servers, log on to the remote server to generate the key, and the public key file to the local computer, written in the Authorized_keys file of this machine;
- Traverse multiple remote servers and distribute the local Authorized_keys files to each server separately.
#!/bin/bash# sshkey.shsource config.EnvCreatelocalkey () {/usr/bin/expect <<_oo_ SpawnSsh-keygen-T Rsa-b2048-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_ SpawnSSH[email protected] $ip expect {"yes/no"{Send"yes\r"; Exp_continue}"*assword:"{Send"$PASSWD \ r" } } Sleep 1Send"ssh-keygen-t rsa-b 2048-n "-F $HOME/.ssh/id_rsa\r"Expect {"(y/n)"{Send"y\r" } } Sleep 1Send"exit\r"expect Eof_oo_/usr/bin/expect <<_oo_ SpawnSCP[Email protected] $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_keysRM-rf/tmp/Id_rsa$ip.pub}copytoremote () {/usr/bin/expect <<_oo_ SpawnSCP$HOME/.SSH/authorized_keys [email protected] $ip: $HOME/.SSH/Authorized_keys Expect {"yes/no"{Send"yes\r"; Exp_continue}"*assword:"{Send"$PASSWD \ r"}} expect Eof_oo_}pullpubkey () { forIpinch${mha_host[@]}; Do if[$IP = = 'ifconfigeth0|grep-op'(? <=inet addr:) \s+'` ]; Then Echo "It ' s local host" ElseCreateremotekeyfi Done}pushauthorizedkeys () { forIpinch${mha_host[@]}; Do if[$IP = = 'ifconfigeth0|grep-op'(? <=inet addr:) \s+'` ]; Then Echo "It ' s local host" ElseCopytoremotefi Done}taskmain () {Createlocalkey Pullpubkey Pushauthorizedkeys}red_echo () {["$HASTTY"==0] &&Echo "[email protected]"||Echo-E"\033[031;[ Email protected]\033[0m"; } Green_echo () {["$HASTTY"==0] &&Echo "[email protected]"||Echo-E"\033[032;[ Email protected]\033[0m"; } Taskmain; RC=$?if[$RC-ne0] ; Then Echo "$ (red_echo Config ssh without password failed!)"Else Echo "$ (green_echo Config ssh without password success!)"fiexit $RC
If there is a better solution, hope message points out, thank you
Shell script configuration ssh password-free login