【问题标题】:How to know current working directory in sftp from python如何从 python 知道 sftp 中的当前工作目录
【发布时间】:2012-09-06 10:01:05
【问题描述】:

我已经用一些细节连接到 sftp,以便从 python 中使用 paramiko 获取一些文件 代码如下

import paramiko
import os
import ftplib

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy( paramiko.AutoAddPolicy() )
ssh.connect('sftp.example.com', username='user', password='pass')
ftp = ssh.open_sftp()
files = ftp.listdir()
print files,"----< Total files"
print ftp.cwd(),"---< Current working diectory"

for feedFile in files:
    if feedFile == 'LifeBridge':
        ftp.chdir(feedFile)

结果

['Emerson', 'Lehighvalley', 'LifeBridge', 'stmaryct'] ----< Total files

File "test_sftp.py", line 11, in <module>
    print ftp.cwd()   ---< Current working diectory
AttributeError: 'SFTPClient' object has no attribute 'cwd'

我正在做的是

  1. 试图找到sftp的当前工作目录

  2. 上面有一个文件列表,作为打印文件的结果,我正在尝试检查它们是文件夹还是文件, 如果它们是文件夹,我想进入LifeBridge 文件夹

最后谁能告诉我以下内容

  1. 如何查看 sftp 的当前工作目录
  2. 如何检查上述列表的结果是文件还是文件夹

【问题讨论】:

  • 您是否检查过对象ftp 是否有可用的getcwd 属性
  • 感谢回复,不,我刚刚尝试过,但没有返回。从某种意义上说没有目录设置正确?以及如何知道代码中提到的上述列表中的数据是文件还是文件夹

标签: python operating-system sftp paramiko


【解决方案1】:

您正在寻找.getcwd() method

返回此 SFTP 会话的“当前工作目录”,由 paramiko 模拟。如果chdir没有设置目录,这个方法会返回None

所以在会话开始时,如果您需要当前工作目录,请先尝试.chdir('.')(更改到当前目录)。

.listdir() 方法只返回目录中项目的名称。如果您需要有关这些文件的更多信息,则需要使用.listdir_attr() method,它会返回SFTPAttributes instances 的列表。

SFTPAttributes 实例通过.st_mode 属性告诉您文件的模式。使用stat.S_ISDIR(mode) function 测试文件是否为目录。

【讨论】:

  • 感谢回复,是的,它没有返回,所以没有设置目录。以及如何查找列表中的数据是文件还是文件夹
猜你喜欢
  • 2012-01-05
  • 1970-01-01
  • 2020-06-10
  • 2018-01-25
  • 2014-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多