本文介绍了如何通过Paramiko获取目录中所有SFTP文件的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
import paramiko
from socket import error as socket_error
import os
server =['10.10.0.1','10.10.0.2']
path='/home/test/'
for hostname in server:
try:
ssh_remote =paramiko.SSHClient()
ssh_remote.set_missing_host_key_policy(paramiko.AutoAddPolicy())
privatekeyfile = os.path.expanduser('~/.ssh/id')
mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile, password='test123')
ssh_remote.connect(hostname, username = 'test1', pkey = mykey)
sftp=ssh_remote.open_sftp()
for i in sftp.listdir(path):
info = sftp.stat(i)
print info.st_size
except paramiko.SSHException as sshException:
print "Unable to establish SSH connection:{0}".format(hostname)
except socket_error as socket_err:
print "Unable to connect connection refused"
这是我的代码.我试图获取远程服务器文件的文件大小.但是下面的错误被抛出.可以请一些指导吗?
This is my code. I tried to get file size of remote server files. But below error was throwing. Can some please guide on this?
错误
Traceback (most recent call last):
File "<stdin>", line 15, in <module>
File "/usr/lib/python2.6/site-packages/paramiko/sftp_client.py", line 337, in stat
t, msg = self._request(CMD_STAT, path)
File "/usr/lib/python2.6/site-packages/paramiko/sftp_client.py", line 624, in _request
return self._read_response(num)
File "/usr/lib/python2.6/site-packages/paramiko/sftp_client.py", line 671, in _read_response
self._convert_status(msg)
File "/usr/lib/python2.6/site-packages/paramiko/sftp_client.py", line 697, in _convert_status
raise IOError(errno.ENOENT, text)
IOError: [Errno 2] No such file
推荐答案
SFTPClient.listdir
仅返回文件名,而不返回完整路径.因此,要在另一个API中使用文件名,您必须添加路径:
SFTPClient.listdir
returns file names only, not a full path. So to use the filename in another API, you have to add a path:
for i in sftp.listdir(path):
info = sftp.stat(path + "/" + i)
print info.st_size
尽管效率低下. Paramiko已经知道大小,您只需使用SFTPClient.listdir
而不是 SFTPClient.listdir_attr
(listdir
内部调用listdir_attr
).
Though that's inefficient. Paramiko knows the size already, you are just throwing the information away by using SFTPClient.listdir
instead of SFTPClient.listdir_attr
(listdir
calls listdir_attr
internally).
for i in sftp.listdir_attr(path):
print i.st_size
这篇关于如何通过Paramiko获取目录中所有SFTP文件的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!