2011-08-23 44 views
2

這裏我使用telnet在遠程主機上建立一個連接,然後在遠程主機上創建一個名爲「file.txt」的文件並存儲結果在file.txt中執行「ls」命令。現在我需要將文件發送到本地主機。我不知道該怎麼做。任何知道它的人都會幫助我。如何通過使用tcl-expect將遠程主機上的文件複製到本地主機

#!/usr/local/bin/expect 
spawn telnet <machine ip> 
expect "login:" 
send "<username>\n" 
expect "Password:" 
send "<password>\n" 
expect "bash" 
send " ls > file.txt\r " 
expect "bash" 
send " cat file.txt \r " 
expect "bash" 
send " command for copying file to the localhost computer\r" 
expect "bash" 
send "exit\r" 
+1

一個強制性的評論:你真的不能使用SSH來做到這一點原生? – kostix

+0

我不知道ssh。 – deva

+0

好的時候去了解它,真的。請參閱Donal的答案後的評論主題了解更多信息。 – kostix

回答

3

你強烈推薦使用sshscp這個任務。

#!/usr/local/bin/expect 

### Factor these out 
set user <username> 
set pass <password> 
set host <machineIP> 

### Get the file list into a file remotely 
spawn ssh [email protected]$host sh -c {ls -1 >file.txt} 
expect { 
    "Password:" { 
     send "$pass\r" 
     exp_continue 
    } 
    eof { 
     close 
    } 
} 
### Copy the file to the local machine 
spawn scp [email protected]${host}:file.txt . 
expect { 
    "Password:" { 
     send "$pass\r" 
     exp_continue 
    } 
    eof { 
     close 
    } 
} 
+0

爲什麼我們不能在這個程序中使用telnet? – deva

+0

這條線的功能是什麼。我的意思是它是做什麼的? -re {(?n)(^。*)$} – deva

+0

一些註釋:我使用'ls -1',因爲*保證*每行一個文件。我使用'$ {host}',因爲':'在變量名中是合法的,但我不希望它是一個。我通常使用'ssh_agent'(或'-i'選項來'ssh'和'scp'),所以我根本不需要提供密碼,但這需要在另一端進行一些設置。 –

相關問題