python使用paramiko远程备份文件并实现两台服务器目录相同

安装 paramiko

pip install paramiko

使用 paramiko

通过paramiko可以实现ssh连接到远程服务器可以实现文件传输、远程控制、远程自动化运维等功能。

  • ssh 连接
ssh = paramiko.SSHClient() # 创建SSH对象
# 允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=hostname,port=port,username=username,password=password)
ssh.exec_command('mkdir test') # 远程执行命令
  • sftp 连接
t = paramiko.Transport((hostname, port))
t.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(t)
# 使用get, put实现上传下载
  • 远程备份代码
import os, sys
cur_dir = os.path.abspath(os.path.dirname(__file__))
pro_dir = os.path.split(cur_dir)[0]
sys.path.append(pro_dir)
import time
import paramiko
# import log
from utils.util import before_days_timestamp, now_time_str, before_days_timestr
from conf.host_cfg import host_param
from utils.log_util import Logger
log = Logger()


class SendFile():
    def __init__(self):
        self.hostname = host_param["128"]["hostname"]
        self.port = host_param["128"]["port"]
        self.username = host_param["128"]["username"]
        self.password = host_param["128"]["password"]
        self.base_path = "/database/data/"
        self.database = '/database/'
        self.days = 7

    def ssh_server(self):
        """
        远程连接128服务器
        :return: 返回ssh 连接对象
        """
        try:
            ssh = paramiko.SSHClient() # 创建SSH对象
            # 允许连接不在know_hosts文件中的主机
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh.connect(hostname=self.hostname, port=self.port, username=self.username,password=self.password)
        except Exception as e:
            # log.logger.debug('SSH Error %s'%e)
            return None
        return ssh

    def sftp_server(self):
        """
        远程连接128服务器用于传输文件
        :return: scp 对象
        """
        try:
            t = paramiko.Transport((self.hostname, self.port))
            t.connect(username=self.username, password=self.password)
            sftp = paramiko.SFTPClient.from_transport(t)
        except Exception as e:
            print(111, e)
            return None
        return sftp

    def set_send_time(self):
        """
        设置转移文件的时间节点(时间戳)如: 转移一周前的, 一个月前的, or两周前的
        :return: 返回设置的时间戳
        """
        before_timestamp = before_days_timestamp(self.days)
        return before_timestamp

    def get_file_path(self):
        """
        获取阿里云服务器上所有的附件的路径及更改日期
        :return:
        """
        file_list = []
        # 获取n天前日期
        b_time = self.set_send_time()
        path_info = os.walk(self.base_path)
        for path, dirs, files in path_info:
            if len(path.split('/')) == 5 and 'screen' not in path:
                if files:
                    # ssh 创建目录
                    is_mk = self.make_dir_list(path)
                    if is_mk:
                        for file in files:
                            file_path = os.path.join(path, file)
                            # 获取文件下载日期
                            d_time = self.get_file_time(file_path)
                            # 对比文件下载日期小于一周前日期的文件放入file_list中
                            if d_time < b_time:
                                file_list.append(file_path)
        if file_list:
            return file_list

    def send_to_128(self, file_list):
        """
        将符合条件的文件传输到128服务器
        :return:
        """
        sftp = self.sftp_server()
        for file in file_list:
            log.debug(file)
            try:
                sftp.put(localpath=file, remotepath=file)
            except Exception as e:
                print(222, e)
                # log.logger.error('send_to_128 error %s'%e)
        return True

    def get_file_time(self, file_path):
        """
        获取要转移文件的时间戳 int类型
        :return: 返回时间戳
        """
        d_time = int(os.path.getctime(file_path))
        return d_time

    def make_dir_list(self,path):
        """
        判断远程(128)服务器是否存在目录, 如果不存在,创建目录并返回True
        :return:
        """
        cmd = 'mkdir -p {}'.format(path)
        ssh = self.ssh_server()
        if ssh:
            try:
                ssh.exec_command(cmd)
            except Exception as e:
                print(333, e)
                # log.logger.error("ssh mkdir -p error %s" % e)
                return False
            return True

    def local_backup(self):
        """
        备份本地n天前的数据,防止传输失败同时文件删除的情况
        :return:
        """
        # 当前时间段%Y%m%d
        t = now_time_str('%Y%m%d')
        n_t = before_days_timestr(self.days, '%Y%m%d')
        tar_file_path = self.database + t + '.tar.gz'
        old_file_path = self.database + n_t + '.tar.gz'
        tar_cmd = "tar -czvf " + tar_file_path + " " + self.base_path
        os.system(tar_cmd)
        if os.path.exists(old_file_path):
            os.remove(old_file_path)

    def main(self):
        # 先对本地文件进行备份
        self.local_backup()
        # 获取需要转移的文件
        file_list = self.get_file_path()
        if file_list:
            # 将文件传输到128服务器
            self.send_to_128(file_list)
        else:
            print('没有新增的附件!')


if __name__ == '__main__':
    send = SendFile()
    a = send.main()

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值