如何通过Paramiko获取目录中所有SFTP文件的大小

时间:2018-07-12 06:16:31

标签: python sftp paramiko filesize

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"

这是我的代码。我试图获取远程服务器文件的文件大小。但是下面的错误被抛出。可以请一些指导吗?

错误

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

1 个答案:

答案 0 :(得分:2)

SFTPClient.listdir仅返回文件名,而不返回完整路径。因此,要在另一个API中使用文件名,您必须添加路径:

function secureFetch(url, method, data) {
  return new Promise((resolve, reject) => {
    fetch(url, {
      method: method || "GET",
      body: JSON.stringify(data),
      mode: "cors",
      headers: {
        "Content-Type": "application/json; charset=utf-8"
      }
    }).then(response => {
      // response only can be ok in range of 2XX
      if (response.ok) {
        // you can call response.json() here too if you want to return json
        resolve(response);
      } else {
        //handle errors in the way you want to
        switch (response.status) {
          case 404:
            console.log('Object not found');
            break;
          case 500:
            console.log('Internal server error');
            break;
          default:
            console.log('Some error occured');
            break;
        }

        //here you also can thorow custom error too
        reject(response);
      }
    })
    .catch(error => {
      //it will be invoked mostly for network errors
      //do what ever you want to do with error here
      console.log(error);
      reject(error);
    });
  });
}

secureFetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(json => console.log(json))
.catch(error => console.log(error));

secureFetch('https://jsonplaceholder.typicode.com/posts/100000000')
.then(response => response.json())
.then(json => console.log(json))
.catch(error => console.log(error));

尽管效率低下。 Paramiko已经知道大小,您只是通过使用for i in sftp.listdir(path): info = sftp.stat(path + "/" + i) print info.st_size 而不是SFTPClient.listdir_attr(内部SFTPClient.listdir调用listdir)来丢弃信息。

listdir_attr