Python,从一个远程服务器处理另一个远程服务器中的文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ZWX2445205419/article/details/86537465
#! -*- coding: utf-8 -*-
import os
import paramiko
import sys
from PIL import Image
"""
1、过滤掉长宽比大于2的图像
2、只保留格式为RGB的图像
"""


class ImageDownload():
    def __init__(self, root, ip, name, passwd, port=22):
        self.root = root
        self.ip = ip
        self.port = port
        self.name = name
        self.passwd = passwd

        self.client = paramiko.SSHClient()
        self._init()

    def _init(self):
        try:
            self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            self.client.connect(self.ip, self.port, self.name, self.passwd, timeout=5)
            self.sftp_client = self.client.open_sftp()  # 建立sftp
        except Exception as e:
            print('failed to open the remote file!')

    def _close(self):
        self.client.close()
        print('download done!')

    def download_pictures(self, remote_dir_path, local_dir_path):
        if not os.path.exists(local_dir_path):
            os.makedirs(local_dir_path)

        def image_filter(image_path):
            """
            过滤:
                1. 打不开的图片
                2. 非RGB图片
                3. 长宽比例大于2的图片
            """
            try:
                image_file = self.sftp_client.open(image_path, 'rb')
                image = Image.open(image_file)
            except Exception as e:
                print('Read {} error: {}'.format(image_path, e))
                return False

            # 判断图片长宽比例
            img_w, img_h = image.width, image.height
            if 0.5 <= (img_w * 1.0 / img_h) <= 2:
                rate = True
            else:
                rate = False

            # 判断图片模式
            if image.mode == 'RGB':
                mode = True
            else:
                mode = False

            # 判断是否满足条件
            if mode and rate:
                return True
            else:
                return False

        print('downloader beginning...')
        self.sftp_client.chdir(self.root)  # 切换到图片根目录
        for image_name in self.sftp_client.listdir(remote_dir_path):
            image_path = os.path.join(remote_dir_path, image_name)
            if image_filter(image_path):
                print(image_path)
                # 保存图片
                try:
                    self.sftp_client.get(image_path, os.path.join(local_dir_path, image_name))
                except Exception as e:
                    print('Save {} failed'.format(image_path))
        self._close()


if __name__ == '__main__':
    root = sys.argv[1]
    ip = sys.argv[2]
    name = sys.argv[3]
    passwd = sys.argv[4]
    downloader = ImageDownload(root, ip, name, passwd)
    downloader.download_pictures('cases-1', '/home/zwx/MyProjects/Datasets/SpamNormal/case_1/')

猜你喜欢

转载自blog.csdn.net/ZWX2445205419/article/details/86537465