Skip to content

Instantly share code, notes, and snippets.

@iampaul83
Last active November 16, 2022 07:32
Show Gist options
  • Save iampaul83/25c0976f53eb98163968ad2b8d1a2b89 to your computer and use it in GitHub Desktop.
Save iampaul83/25c0976f53eb98163968ad2b8d1a2b89 to your computer and use it in GitHub Desktop.
ssh-copy-id script

目標

  1. 實現ssh免打密碼登入
  2. 自動化上面的過程
    • 因為要實現免打密碼登入,一開始還是要打一次密碼

NOTE: 以下的範例都是在macOS10.12中執行,不同OS或版本可能會有出入

ssh免密登入

首先要先產生金鑰,詳細步驟請看git官網教學

接著要把產生的pub key傳到要免密登入的server上,如果照上面的教學做,產生的public key會在~/.ssh/id_rsa.pub,傳到server上的一行snippet如下:

cat ~/.ssh/id_rsa.pub | ssh username@server 'cat >> .ssh/authorized_keys'

你會發現,執行這行他會要求你回答"yes",並且輸入密碼。


自動化

NOTE: 再expect跑上面那個snippet (cat ~/.ssh/id_rsa.pub .......) 我還沒成功實作,以下是用ssh-copy-id這個程式實作

ssh-copy-id: linux本身好像就有了,mac可以用brew install ssh-copy-id安裝

用法: ssh-copy-id username@server,效果同cat ~/.ssh/id_rsa.pub | ssh username@server 'cat >> .ssh/authorized_keys'

為了自動化上面這個過程,可以使用expect這個程式,新增一個檔案叫做__ssh-copy-id.expect__

記得修改裡面的密碼

#!/usr/bin/expect
set timeout 9
set hostname     [lindex $argv 0]

spawn ssh-copy-id $hostname

expect {
    timeout { send_user "\nFailed to get password prompt\n"; exit 1 }
    eof { send_user "\nSSH failure for $hostname\n"; exit 1 }

    "*re you sure you want to continue connecting" {
        send "yes\r"
        exp_continue
    }
    "*assword*" {
        send  "PASSWORD\r"
        interact
        exit 0
    }
}

以下這行打完就可以自動把完成輸入密碼了。

$ expect ssh-copy-id.expect username@server

最後因為server有很多個,跑個迴圈,以下程式自動把key傳到192.168.2.181~188八個server上

ssh-copy-id.sh

#!/bin/bash
for i in {1..8}
   do
      expect ssh-copy-id.expect root@192.168.2.18$i
done
$ bash ssh-copy-id.sh
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment