expect 批量分发密钥对

该脚本是一个自动分发免密要登录的脚本,运行后可对特定主机组进行自动分发密钥对操作。

vim shell.exp

#!/usr/bin/expect

set timeout 10
set hostname [lindex $argv 0]
set username [lindex $argv 1]
set password [lindex $argv 2]

spawn ssh-copy-id $username@$hostname

expect {
            "Are you sure you want to continue connecting (yes/no)?" {
            send "yes\r"
            expect "*password:"
            send "$password\r"
            }

            "*password:" {
            send "$password\r"
            }
            "Now try logging into the machine" {
            }
        }
expect eof

一个bash搞定,在bash中,用expect -c "" 把expect语句包起来,将expect -c "" 中的双引号加上反斜杠

#!/bin/bash

USER=root
PASSWD=1233

# yum install -y expect

for HOST in 192.168.1.{1..10}
do
        echo "------------------>" $HOST "-----------------------------"
/usr/bin/expect -c "
spawn ssh-copy-id $USER@$HOST;
expect {
            \"Are you sure you want to continue connecting (yes/no)?\" {
            send \"yes\r\"
            expect \"*password:\"
            send \"$PASSWD\r\"
            }

            \"*password:\" {
            send \"$PASSWD\r\"
            }
            \"Now try logging into the machine\" {
            }
        }
expect eof
"
done
posted @ 2019-05-18 20:47  lyshark  阅读(415)  评论(0编辑  收藏  举报

loading... | loading...
博客园 - 开发者的网上家园