# ssh免密分发脚本

需要远程服务器用户名和密码一致

#!/bin/bash
password="123456"
IP_LIST=(10.10.155.130)  

home=`cd ~|pwd`
echo $home
for ip in ${IP_LIST[@]}
do

# 上传本机的公钥id_rsa.pub 到远程主机
    expect <<EOF
	set timeout 4
	spawn scp -p $home/.ssh/id_rsa.pub app@$ip:/root/.ssh/authorized_keys
	expect {
		"*yes/no*" {
			send "yes\n"; exp_continue
		}
		"password" {
			exp_send "$password\n"
			send_user "\n\n############ set password ok ############\n"
			exp_continue
		}
	}


	send_user "\n########## upload success #############\n"
	
EOF

# 修改远程主机的sshd_config 开启公钥登录,支持免密
	expect << EOF
	#login modify sshd_config
	set timeout 1
	spawn ssh app@$ip
	expect "password" { send "$password\n" }
	expect "*]#" 
		send "sed -i 's/\\\s\\\.ssh\\\/authorized_keys/ \\\/root\\\/\\\.ssh\\\/authorized_keys/g' /etc/ssh/sshd_config\n"
		send "service sshd restart \n"
	expect "*]#"
		send "exit\n"
EOF


done

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45