自动ssh免密配置脚本
因为调用ssh需要免密,使用脚本加配置文件自动批量免密。脚本如下
hostip=$1 name=$2 PASSWORD=$3
需要脚本添加上面三个参数或者通过循环一个host文件实现批量即可。
#!/bin/bash #yum安装expect #yum -y install expect #PWD_1是登陆密码,可以自己设定 #PASSWORD=123456 #hosts="master slave1 slave2" # key_generate() { expect -c "set timeout -1; spawn ssh-keygen -t rsa; expect { {Enter file in which to save the key*} {send -- \r;exp_continue} {Enter passphrase*} {send -- \r;exp_continue} {Enter same passphrase again:} {send -- \r;exp_continue} {Overwrite (y/n)*} {send -- n\r;exp_continue} eof {exit 0;} };" } auto_ssh_copy_id () { expect -c "set timeout -1; spawn ssh-copy-id -i $HOME/.ssh/id_rsa.pub $1@$2; expect { {Are you sure you want to continue connecting *} {send -- yes\r;exp_continue;} {*password:} {send -- $3\r;exp_continue;} eof {exit 0;} };" } check_cmd () { if [[ $? == 0 ]];then echo "$1 SUCCESS" else echo "$1 ERROR" exit fi } chmod +x ssh_init.exp if [[ ! -e $HOME/.ssh/id_rsa.pub ]]; then key_generate && check_cmd "ssh key creat" fi hostip=$1 name=$2 PASSWORD=$3 auto_ssh_copy_id $name $hostip $PASSWORD ./ssh_init.exp $name $hostip $PASSWORD check_cmd "ssh scripts run cmd"
做一个秘钥检测,检测是否成功。
ssh_init.exp 内容如下
#!/usr/bin/expect -f set timeout 2 set name [lindex $argv 0] set node [lindex $argv 1] set pawd [lindex $argv 2] spawn ssh ${name}@${node} expect { "*yes/no*" {send "yes\n";exp_continue} "*password:" {send "$pawd\r"} } #expect "*${name}@${node}*" #send "ssh-keygen -t rsa -P ''\r" #expect "*ssh/id_rsa):" #send "\r" #expect { # "Overwrite (y/n)?" {send "y\n";exp_continue} # "*${name}@${node}*" {send "exit\r"} #} expect eof exit