Python中通过SFTP连接后如何列出目录下的所有文件夹和文件 [英] How to list all the folders and files in the directory after connecting through SFTP in Python

查看:81
本文介绍了Python中通过SFTP连接后如何列出目录下的所有文件夹和文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Python 并尝试连接到 SFTP,想从那里检索 XML 文件,需要将它放在我的本地系统中.代码如下:

import paramikosftpURL = 'sftp.somewebsite.com'sftpUser = '用户名'sftpPass = '密码'ssh = paramiko.SSHClient()# 自动添加密钥,无需人工干预ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())ssh.connect(sftpURL, 用户名=sftpUser, 密码=sftpPass)ftp = ssh.open_sftp()文件 = ftp.listdir()打印文件

这里连接成功.现在我想查看所有文件夹和所有文件,需要进入所需的文件夹以从那里检索 XML 文件.

最后我的目的是在连接到 SFTP 服务器后查看所有文件夹和文件.

在上面的代码中我使用了 ftp.listdir() 通过它我得到了像下面这样的输出

['.bash_logout', '.bash_profile', '.bashrc', '.mozilla', 'testfile_248.xml']

我想知道是否只有这些文件?

我上面使用的命令也可以查看文件夹吗?

查看所有文件夹和文件的命令是什么?

解决方案

一个快速的解决方案是检查 ftp.listdir() 中每个对象的 lstat 的输出.

这是列出所有目录的方法.

<预><代码>>>>对于 ftp.listdir() 中的 i:... lstatout=str(ftp.lstat(i)).split()[0]...如果 lstatout 中的d":打印 i,是一个目录"...

文件是相反的搜索:

<预><代码>>>>对于 ftp.listdir() 中的 i:... lstatout=str(ftp.lstat(i)).split()[0]...如果 'd' 不在 lstatout 中:打印 i,'是一个文件'...

I am using Python and trying to connect to SFTP and want to retrieve an XML file from there and need to place it in my local system. Below is the code:

import paramiko

sftpURL   =  'sftp.somewebsite.com'
sftpUser  =  'user_name'
sftpPass  =  'password'

ssh = paramiko.SSHClient()
# automatically add keys without requiring human intervention
ssh.set_missing_host_key_policy( paramiko.AutoAddPolicy() )

ssh.connect(sftpURL, username=sftpUser, password=sftpPass)

ftp = ssh.open_sftp()
files = ftp.listdir()
print files

Here connection is success full. And now I want to see all the folders and all the files and need to enter in to required folder for retrieving the XML file from there.

Finally my intention is to view all the folders and files after connecting to SFTP server.

In the above code I had used ftp.listdir() through which I got output as some thing like below

['.bash_logout', '.bash_profile', '.bashrc', '.mozilla', 'testfile_248.xml']

I want to know whether these are the only files present?

And the command I used above is right to view the folders too?

What is the command to view all the folders and files?

解决方案

One quick solution is to examine the output of lstat of each object in ftp.listdir().

Here is how you can list all the directories.

>>> for i in ftp.listdir():
...     lstatout=str(ftp.lstat(i)).split()[0]
...     if 'd' in lstatout: print i, 'is a directory'
... 

Files are the opposite search:

>>> for i in ftp.listdir():
...     lstatout=str(ftp.lstat(i)).split()[0]
...     if 'd' not in lstatout: print i, 'is a file'
... 

这篇关于Python中通过SFTP连接后如何列出目录下的所有文件夹和文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆