天天看點

linux scp輸入密碼無響應,scp 在腳本中使用輸入密碼的解決方法

以前用腳本scp檔案時,都是以.ssh打通為基礎的。

但是在腳本中使用scp在機器之間拷貝檔案,輸入密碼成為問題。

第一種方法,用到了expect。

腳本如下:

#! /usr/bin/expect -f

spawn scp 1 [email protected]:

expect "*password:"

send "your password\r"

expect eof

當然不隻是scp,其它指令也可以用expect自動化

循環處理:

spawn scp 1 [email protected]:

for { set i 1 } {$i<500} {incr i} {

expect {"*password:" {send "koven\r"}

"*(yes/no)*" {send "yes\r"}

}

}

注意大括号之間有空格 。

第二種方法,使用密鑰檔案。

這裡假設主機A(192.168.100.3)用來獲到主機B(192.168.100.4)的檔案。

在主機A上執行如下指令來生成配對密鑰:

ssh-keygen -t rsa

遇到提示回車預設即可,公鑰被存到使用者目錄下.ssh目錄,比如root存放在:

/root/.ssh/id_rsa.pub

将 .ssh 目錄中的 id_rsa.pub 檔案複制到 主機B 的 ~/.ssh/ 目錄中,并改名為 authorized_keys,

到主機A中執行指令和主機B建立信任,例(假設主機B的IP為:192.168.100.4):

scp ~/.ssh/id_rsa.pub 192.168.100.4:/root/.ssh/authorized_keys

下面就可以用scp、ssh指令不需要密碼來擷取主機B的檔案了

ssh 192.168.100.4 回車就不需要密碼了。

注:其實id_rsa.pub内容添加到對方機器的authorized_keys中就行了。

-----------------------------------------------------------------------------------------------------

#!/usr/bin/expect -f

set password 密碼

spawn scp 使用者名@目标機器ip:拷貝檔案的路徑 存放本地檔案的路徑

set timeout 300

expect "使用者名@目标機器ip's password:" #注意:這裡的“使用者名@目标機器ip” 跟上面的一緻

set timeout 300

send "$password\r"

set timeout 300

send "exit\r"

expect eof

附:scp參數

-r:拷貝目錄

-c:允許壓縮

一個完整的例子

#!/usr/bin/expect -f

set password 123456

#download

spawn scp [email protected]:/root/a.wmv /home/yangyz/

set timeout 300

expect "[email protected]'s password:"

set timeout 300

send "$password\r"

set timeout 300

send "exit\r"

expect eof

#upload

spawn scp /home/yangyz/abc.sql [email protected]:/root/test.sql

set timeout 300

expect "[email protected]'s password:"

set timeout 300

send "$password\r"

set timeout 300

send "exit\r"

expect eof

########

PS:需要先安裝expect