2013-01-31 75 views
3

我試圖從localServer之間的兩個服務器之間複製文件,比如從server-Aserver-B。我在Python中使用paramiko包。Python - 在兩個遠程服務器之間傳輸文件,執行python腳本

所以有三個服務器,即localServer,server-Aserver-B。請參閱下面的代碼,這是不言自明的,請讓我知道我要出錯的地方。

算法我使用:

  1. 我試圖從localServer運行paramiko_test.py文件。
  2. paramiko_test.py執行copy.py文件在server-A
  3. copy.py使用SFTP將文件source.txtserver-A改爲server-B

當我從server-A運行copy.py時,它工作正常。但是,當我從localServer(它間接執行copy.pyserver-A)運行paramiko_test.py時,它不起作用!

從日誌,我知道有一個從server-Aserver-B成功的連接,但之後,SFTP部分不工作!

問題:我們可以調用SFTP客戶端內的SFTP客戶端嗎?有沒有更好的方法在兩臺服務器之間複製文件?

請幫我我哪裏錯了。

服務器-A,文件:copy.py:

import paramiko 

ssh = paramiko.SSHClient() 
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
ssh.connect('<server-B-IP>', username='serverB', password='passwd') 

print "connected successfully!" 

sftp = ssh.open_sftp() 
print sftp 
sftp.put('source.txt','/home/serverB/destination.txt') 
sftp.close() 
print "copied successfully!" 

ssh1.close() 
exit() 

的LocalServer,paramiko_test.py:

import paramiko 

ssh = paramiko.SSHClient() 
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
ssh.connect('<server-A-IP>', username='serverA', password='passwd') 

print "connected successfully!" 

stdin, stdout, stderr = ssh.exec_command("python /home/username/copy.py") 

print stdout.readlines() 

print "copied successfully!" 

ssh.close() 
exit() 

stderr.readlines()的輸出是:

Traceback (most recent call last): 
File "/home/sitaram/sumanth/test_progs/copy.py", line 12, in <module> 
sftp1.put('./sumanth_temp.txt','/home/ncloudadmin/sumanth.txt') 
File "/usr/lib/pymodules/python2.6/paramiko/sftp_client.py", line 558, in put 
file_size = os.stat(localpath).st_size 
OSError: [Errno 2] No such file or directory: './sumanth_temp.txt' 
+1

您看過織物嗎?它比Paramiko更容易[使用文件](http://docs.fabfile.org/en/1.5/api/contrib/files.html),並且可以執行諸如[在遠程服務器上放置文件]( http://docs.fabfile.org/en/1.5/api/core/operations.html#fabric.operations.put) –

+0

嗨,亞歷克斯,謝謝你的回覆。我看着Fabric,我沒有看到Fabric支持兩臺遠程主機之間的文件傳輸,在另一臺本地服務器上運行腳本。或者它是由Fabric支持的?請幫忙。 –

+0

你可以SSH進入遠程服務器之一,然後通過SFTP/SCP?你在'sterr'中得到了什麼? –

回答

5

問題已經過時了,可能不再相關,但也許對其他人有用。問題出在你的copy.py中。

sftp.put('source.txt','/home/serverB/destination.txt') 

where is source.txt located?要麼提供完整路徑,要麼文件總是位於與copy.py相同的目錄中,您可以修改您的paramiko_test.py

ssh.exec_command("cd /home/username/; python /home/username/copy.py") 
+0

'sftp.put'或'sftp.get'確保'ssh.exec_command'不會執行,直到他們是通過傳輸文件完成的? – weefwefwqg3

相關問題