linux ssh 不用密碼自動登錄的幾種方法

http://www.kuaiwenba.com

1. 自動ssh/scp方法==

A爲本地主機(即用於控制其他主機的機器) ;
B爲遠程主機(即被控制的機器Server), 假如ip爲192.168.60.110;
A和B的系統都是Linux

在A上運行命令:
# ssh-keygen -t rsa (連續三次回車,即在本地生成了公鑰和私鑰,不設置密碼)
# ssh [email protected] "mkdir .ssh" (需要輸入密碼)
# scp ~/.ssh/id_rsa.pub [email protected]:.ssh/id_rsa.pub (需要輸入密碼)

在B上的命令:
# touch /root/.ssh/authorized_keys (如果已經存在這個文件, 跳過這條)
# cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys (將id_rsa.pub的內容追加到authorized_keys 中)

回到A機器:

# ssh [email protected] (不需要密碼, 登錄成功) 

如出現Agent admitted failure to sign using the key錯誤

則在A機器上:

# ssh-add   ~/.ssh/id_rsa  



2. 控制n個機器如上所述自動登錄
那就需要n對鑰匙(密鑰和公鑰), ssh-keygen 命令可以隨意更改鑰匙對的名字, 比如:
# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): /root/.ssh/id_rsa_192.168.60.110

這樣私鑰和公鑰的名字分別就是: id_rsa_192.168.60.110和 id_rsa_192.168.60.110.pub;然後將 id_rsa_192.168.60.110.pub 文件的內容, 追加到sever的 ~/.ssh/authorized_keys文件中,最後, 在本地用ssh命令的 -i 參數指定本地密鑰, 並登錄:
# ssh -i /root/.ssh/id_rsa_192.168.60.110 [email protected]

scp也是一樣的
# scp -i /root/.ssh/id_rsa_192.168.60.110 filename [email protected]:/home/someone

在文件.bashrc中加下兩行,每次做同樣的操作就不用敲入這樣長的命令了:
alias sshcell='ssh -i /root/.ssh/id_rsa_192.168.60.110 [email protected]'
alias scpcell='scp -i /root/.ssh/id_rsa_192.168.60.110 filename [email protected]:/home/someone'

這樣,直接鍵入一下指令實現ssh和scp自動登錄:
# sshcell
# scpcell


3. 自動ssh/scp腳本
如果需要從A,到B,然後才能夠到C,那麼需要ssh和scp兩次,是比較麻煩的。
ssh自動登錄:
#!/usr/bin/expect -f
set timeout 30
spawn ssh weiqiong@B
expect "password:"
send "pppppp\r"
expect "]*"
send "ssh weiqiong@C\r"
expect "password:"
send "pppppp\r"
interact


scp從A拷貝文件到C:
#!/usr/bin/expect -f
set timeout 300
set file [lindex $argv 0]
spawn scp $file weiqiong@B:/home/weiqiong
expect "password:"
send "pppppp\r"
expect "]*"
spawn ssh weiqiong@B
expect "password:"
send "pppppp\r"
expect "]*"
send "scp $file weiqiong@C:/home/weiqiong\r"
expect "password:"
send "pppppp\r"
expect "]*"
exit
interact

scp從C拷貝文件到A:
#!/usr/bin/expect -f
set timeout 300
set file [lindex $argv 0]
spawn ssh weiqiong@B
expect "password:"
send "pppppp\r"
expect "]*"
send "scp weiqiong@C:/home/weiqiong/$file .\r"
expect "password:"
send "pppppp\r"
expect "]*"
send "exit\r"
expect "]*"
spawn scp weiqiong@B:/home/weiqiong/$file .
expect "password:"
send "pppppp\r"
interact

4. 建立ssh/scp通道
比如說我的機器是A,中間服務器爲B,目標服務器是C
從A可以ssh到B,從B可以ssh到C,但是A不能直接ssh到C
現在展示利用ssh通道技術從A直接傳輸文件到C
1. ssh -L1234:C:22 userid@B
input B's password
(1234是本機A的空閒端口,該指令需要A機器上的root用戶權限,實際上是在本機1234端口建立了一個通道)

2. 打開一個新的console,鍵入:
scp -P1234 filename userid@localhost:
input C's password 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章