pssh expect 使用

Posted by Sunday on 2019-07-01

批量添加密钥

有两种情况,一种是直接输入密码,就像基线版本;另一种情况是会先提示添加主机到known_hosts。

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
vim addkeys.sh 

#!/usr/bin/expect
set timeout 60
set user root
set password 123456
set key_path /home/test/.ssh/id_rsa.pub

for {set i 101} {$i < 201} {incr i} {
spawn ssh-copy-id -i $key_path -p 22 $user@192.168.56.$i
expect {
#first connect, no public key in ~/.ssh/known_hosts
"Are you sure you want to continue connecting (yes/no)?" {
send "yes\r"; exp_continue
}
#already has public key in ~/.ssh/known_hosts
"install the new keys" {
send "\r"; exp_continue
}
"password:" {
send "$password\r"; exp_continue
}
"Now try logging into the machine" {
#it has authorized, do nothing!
; exp_continue
}
}
}
1
2
chmod +x addkeys.sh
./addkeys.sh

批量删除

添加完密钥之后,发现部分机器不能免密登录。检查客户机中的authorized_keys文件,发现添加了两次密钥。于是决定删除重新添加。

1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/expect 
set timeout 30
set user root
set password 123456

for {set i 101} {$i < 201} {incr i} {
spawn ssh $user@192.168.56.$i "rm /home/test/.ssh/authorized_keys"
expect {
"password:" { send "$password\r"}
"No route to host" { send "\r" }
}
}

批量修改权限
删除后重新添加,依然无法登录,后来发现,是目录权限的问题。用户目录权限是750,~/.ssh权限是700, ~/.ssh/authorized_keys权限是600。

1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/expect 
set timeout 30
set password 123456

for {set i 101} {$i < 201} {incr i} {
spawn ssh test@192.168.56.$i -t "sudo chmod 750 /home/test/ && sudo chmod 700 /home/test/.ssh && sudo chmod 600 /home/test/.ssh/authorized_keys"
expect {
"password:" { send "$password\r"; exp_continue }
"password for test" { send "$password\r"; exp_continue }
"No route to host" { send "\r" }
}
}

设置sudo免密

以上,假设已经实现了批量添加密钥,也就是实现了所有客户机的免密登录。但是,在客户机执行sudo命令的时候,会提示输入密码,也是很麻烦,所以接下来设置sudo免密执行。

1
2
3
4
5
6
7
8
9
10
11
12
13
#!/usr/bin/expect 
set timeout 10
set password 123456

for {set i 101} {$i <= 200} {incr i} {
spawn ssh test@192.168.56.$i -t "sudo -i"
expect "password for test:"
send "$password\r"
expect "*#"
send "echo test ALL = NOPASSWD: ALL >> /etc/sudoers \r"
expect "*#"
send "exit\r"
}

链接

使用PSSH批量管理Linux进阶篇