当SFTP对象存储在字典中时,为什么Paramiko会提高EOFError()?

时间:2011-03-17 16:47:08

标签: python ssh sftp paramiko

我正在编写一个应用程序,我正在编写通过SSH下载和上传文件到其他框的文件。我遇到的问题是我可以获得(下载)文件,但是当我尝试将它们(上传)到另一台服务器上时,我得到一个EOFError()异常。当我在paramiko \ sftp.py中查看_write_all()时,似乎错误是在它无法向流中写入任何数据时引起的?我没有网络编程经验,所以如果有人知道它正在尝试做什么,并且能够与我沟通,我会很感激。

我写了一个简化版本的函数来处理我的连接为ssh()。 runCommand()显示了我的应用程序中的上传失败,而simpleTest()显示了sftp put是如何工作的,但除了我的SFTP对象的存储方式之外,我看不出runCommand()和simpleTest()之间的任何区别。一个存储在字典中,另一个存储在字典中。似乎字典是下载文件不起作用的问题,但事实并非如此。

有没有人知道可能导致此行为的原因,或者如果这种方式导致问题,可以推荐另一种方法来管理我的连接?

我正在使用带有Paramiko 1.7.6的Python 2.7。我已经在Linux和Windows上测试了这段代码并得到了相同的结果。

编辑:现在包含的代码。

import os
import paramiko

class ManageSSH:
     """Manages ssh connections."""
    def __init__(self):
        self.hosts = {"testbox": ['testbox', 'test', 'test']}
        self.sshConnections = {}
        self.sftpConnections = {}
        self.localfile = "C:\\testfile"
        self.remotefile = "/tmp/tempfile"
        self.fetchedfile = "C:\\tempdl"

    def ssh(self):
        """Manages ssh connections."""
        for host in self.hosts.keys():
            try:
                self.sshConnections[host]
                print "ssh connection is already open for %s" % host
            except KeyError, e:         # if no ssh connection for the host exists then open one
                # open ssh connection
                ssh = paramiko.SSHClient()
                ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                ssh.connect(self.hosts[host][0], 22, self.hosts[host][1], self.hosts[host][2])
                self.sshConnections[host] = ssh
                print "ssh connection to %s opened" % host
            try:
                self.sftpConnections[host]
                print "sftp connection is already open for %s" % host
            except KeyError, e:
                # open sftp connection
                ssh = paramiko.SSHClient()
                ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                ssh.connect(self.hosts[host][0], 22, self.hosts[host][1], self.hosts[host][2])
                self.sftpConnections[host] = ssh.open_sftp()
                print "sftp connection to %s opened" % host

    def runCommand(self):
        """run commands and return output"""
        for host in self.hosts:
            command = "if [ -d /tmp ]; then echo -n 1; else echo -n 0; fi"
            stdin, stdout, stderr = self.sshConnections[host].exec_command(command)
            print "%s executed on %s" % (command, host)
            print "returned %s" % stdout.read()
            self.sftpConnections.get(self.remotefile, self.fetchedfile)
            print "downloaded %s from %s" % (self.remotefile, host)
            self.sftpConnections[host].put(self.localfile, self.remotefile)
            print "uploaded %s to %s" % (self.localfile, host)
            self.sftpConnections[host].close()
            self.sshConnections[host].close()

    def simpleTest(self):
        host = "testbox"
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(host, 22, 'test', 'test')
        sftp = ssh.open_sftp()
        print "sftp connection to %s opened" % host
        sftp.get(self.remotefile, self.fetchedfile)
        print "downloaded %s from %s" % (self.localfile, host)
        sftp.put(self.localfile, self.remotefile)
        print "uploaded %s to %s" % (self.localfile, host)
        sftp.close()

if __name__ == "__main__":
    test = ManageSSH()
    print "running test that works"
    test.simpleTest()
    print "running test that fails"
    test.ssh()
    test.runCommand()

输出:

running test that works
sftp connection to testbox opened
downloaded C:\testfile from testbox
uploaded C:\testfile to testbox
running test that fails
ssh connection to testbox opened
sftp connection to testbox opened
if [ -d /tmp ]; then echo -n 1; else echo -n 0; fi executed on testbox
returned 1
downloaded /tmp/tempfile from testbox
Traceback (most recent call last):
  File "paramikotest.py", line 71, in <module>
    test.runCommand()
  File "paramikotest.py", line 47, in runCommand
    self.sftpConnections[host].put(self.localfile, self.remotefile)
  File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 561, in put

    fr = self.file(remotepath, 'wb')
  File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 245, in open
    t, msg = self._request(CMD_OPEN, filename, imode, attrblock)
  File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 627, in _request
    num = self._async_request(type(None), t, *arg)
  File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 649, in _async_request
    self._send_packet(t, str(msg))
  File "C:\Python27\lib\site-packages\paramiko\sftp.py", line 172, in _send_packet
    self._write_all(out)
  File "C:\Python27\lib\site-packages\paramiko\sftp.py", line 138, in _write_all

    raise EOFError()
EOFError

3 个答案:

答案 0 :(得分:7)

我能够解决我的问题。我原本应该使用Paramiko.Transport,然后使用SFTPClient创建paramiko.SFTPClient.from_transport(t),而不是使用open_sftp()中的SSHClient()

以下代码有效:

t = paramiko.Transport((host, 22))  
t.connect(username=username, password=password)  
sftp = paramiko.SFTPClient.from_transport(t)

答案 1 :(得分:2)

我认为,使用ssh = SSHClient()创建一个SSHClient-Object,然后使用sftp = ssh.open_sftp()创建一个sftp-object。虽然你只想使用sftp,你将ssh存储在一个局部变量中,然后获取gc'd,但是,如果ssh是gc'd,则sftp会神奇地停止工作。不知道为什么,但试着把你的sftp存在的时间存储起来。

答案 2 :(得分:0)

阅读完编辑后,我认为问题就在这里

stdin, stdout, stderr = self.sshConnections[host].exec_command(command)

这条线显然断开了ftp的事情

<强> EDITED