1. 程式人生 > >使用expect實現ssh免密碼登陸

使用expect實現ssh免密碼登陸

使用expect向ip列表檔案中的ip主機,執行ssh-copy-id命令複製金鑰,以實現ssh免密登陸。

安裝expect

yum install -y expect

生成金鑰對

ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa

指令碼

//shell指令碼內容
# -------------------------
vim ssh-copy-id.sh

#!/bin/bash
#
[ $# -gt 0 -a -f "$1" ] || exit 1

cat $1 | while read ip ;do
    user='root'
    password='centos'

    expect ./ssh-copy-id.exp $ip $user $password
done




//expect指令碼內容
-------------------------
vim ssh-copy-id.exp

#!/usr/bin/expect
set ip [lindex $argv 0]
set user [lindex $argv 1]
set password [lindex $argv 2]
set timeout 10
spawn ssh-copy-id 
[email protected]
$ip expect { "yes/no" { send "yes\n";exp_continue } "password" { send "$password\n" } } expect eof //iplists檔案 ------------------------- vim iplists.txt 192.168.10.101 192.168.10.102 192.168.10.103 192.168.10.104 192.168.10.105 //呼叫指令碼 sh ssh-copy-id.sh iplists.txt