1. 自動ssh/scp方法
A為本地主機(即用於控制其他主機的機器) ;
B為遠程主機(即被控制的機器Server), 假如ip為192.168.60.110;
A和B的系統都是Linux
在A上運行命令:
# ssh-keygen -t rsa (連續三次斷行符號,即在本地產生了公開金鑰和私密金鑰,不設定密碼)
# ssh root@192.168.60.110 "mkdir .ssh" (需要輸入密碼)
# scp ~/.ssh/id_rsa.pub root@192.168.60.110:.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 root@192.168.60.110 (不要求輸入密碼, 登入成功)
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 someone@192.168.60.110
scp也是一樣的
# scp -i /root/.ssh/id_rsa_192.168.60.110 filename someone@192.168.60.110:/home/someone
在檔案.bashrc中加下兩行,每次做同樣的操作就不用敲入這樣長的命令了:
alias sshcell='ssh -i /root/.ssh/id_rsa_192.168.60.110 someone@192.168.60.110'
alias scpcell='scp -i /root/.ssh/id_rsa_192.168.60.110 filename someone@192.168.60.110:/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 "ppppppr"
expect "]*"
send "ssh weiqiong@Cr"
expect "password:"
send "ppppppr"
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 "ppppppr"
expect "]*"
spawn ssh weiqiong@B
expect "password:"
send "ppppppr"
expect "]*"
send "scp $file weiqiong@C:/home/weiqiongr"
expect "password:"
send "ppppppr"
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 "ppppppr"
expect "]*"
send "scp weiqiong@C:/home/weiqiong/$file .r"
expect "password:"
send "ppppppr"
expect "]*"
send "exitr"
expect "]*"
spawn scp weiqiong@B:/home/weiqiong/$file .
expect "password:"
send "ppppppr"
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