【问题标题】:sftp.get python paramiko [no such file]sftp.get python paramiko [没有这样的文件]
【发布时间】:2014-02-05 18:35:21
【问题描述】:

我正在编写一个 Python 脚本,需要下载一个远程 xml 文件来解析它。

我正在使用 paramiko。

这是脚本:

def copyFile(ip, user, pwd, remotePath, localPath):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
    ssh.connect(ip,username=user,password=pwd)
    ### Copy remote file to server        
    sftp = ssh.open_sftp()
    sftp.get(remotePath,localPath)
    sftp.close()
    ssh.close()
    return ["OK",0,0]
except IOError as e:
    flash(str(e)+" IOERROR")
    return ["IOERROR: " + str(e),0,0]
except Exception as e:
    flash(str(e)+" OTHER EXCEPTION")
    return ["Error: " + str(e),0,0]

代码返回,IOError 表示文件不存在。

但是如果我将变量换成字符串,它就可以完美运行。:

   `sftp.get("/etc/conf/file-cfg.xml","./conf/file-cfg.xml")` 

变量被正确传递:

    `copyFile(ip,username,pwd,"/etc/conf/"+i,"."+i)`

我浪费了很多时间试图找出问题所在,但没有成功。

我的远程机器:Ubuntu 13.10 x64 本地机器:Windows 7 x64

【问题讨论】:

    标签: paramiko


    【解决方案1】:

    我遇到了同样的问题,但后来发现后面有一个 \n 字符,这是看不见的。

    所以我建议调用 strip() 方法来删​​除不可见的前导/尾随字符,这可能是有问题的字符

    strip() 在我身边工作。

    【讨论】:

      【解决方案2】:

      我在使用 Paramiko 时遇到了类似的问题。我正在连接字符串来创建我的路径

      localpath = root + '\' + filename
      remotepath = root + '\' + filename
      

      我发现字符串有效,但连接的字符串无效。呜呜呜

      local_path = str(localpath)
      remote_path = str(remotepath)
      sftp.get(remote_path,local_path)
      

      它可能看起来很难看,但它对我有用。

      【讨论】:

        【解决方案3】:

        对于此类字符串,我最好使用原始字符串文字。喜欢

        remotePath = r"/etc/conf/file-cfg.xml"
        

        或者,更好的是,使用路径相关的函数来创建独立于平台的路径。

        【讨论】:

          最近更新 更多