2013-01-31 76 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

相关问题