windows环境下用python实现对远程服务器进行备份文件的检查

# -*- coding:utf-8-*-

import paramiko
import time
import re
import os
import configparser
from datetime import datetime, timedelta

#函数:获取上周某天(如:上周一)对应的日期
def get_previous_byday(dayname, start_date=None):
    weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
    if start_date is None:
        start_date = datetime.today()
    day_num = start_date.weekday()
    day_num_target = weekdays.index(dayname)
    days_ago = (7 + day_num - day_num_target) % 7
    if days_ago == 0:
        days_ago = 7
    target_date = start_date - timedelta(days=days_ago)
    return target_date

def get_Connect():
    print('正在连接服务器,请稍后...')
    # 创建SSH对象
    ssh = paramiko.SSHClient()
    # 允许连接不在know_hosts文件中的主机
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    # 连接服务器
    try:
        # 服务器地址
        ip = '192.168.1.0'
        # 访问端口
        port = 22
        # 连接用户名
        username = 'test'
        # 密码
        passwd = 'test'
        ssh.connect(ip, port, username, passwd)
        print('连接结果:' + str(ssh))
    except:
        print('连接' + ip + '失败!')
        exit(101)
    else:
        print('连接' + ip + '成功!')
        return ssh

def close_Connect(ssh):
    # 连接服务器
    try:
        ssh.close()
    except:
        print('断开失败!')
    else:
        print('断开成功!')

#函数:根据指定路径dir,检查某一天date的文件数量和大小情况
def check_backup(ssh, dir, date):
    # print(dir)
    bat = 'cmd.exe /c "if exist "' + dir + '" (echo y) else (echo n)"'
    # print(bat.encode("gbk"))
    # exit(000)
    # 如果执行的命令中带有中文,需要将bat命令进行encode编码加密处理
    stdin, stdout, stderr = ssh.exec_command(bat.encode("gbk"))
    result = stdout.read().decode("gbk")
    # print(result)
    if result.strip() == 'y':
        print("\033[0;32m%s\033[0m" % "目录存在!")
    else:
        print("\033[0;31m%s\033[0m" % "目录不存在!")
        return

    # 获取指定目录下的文件、文件夹信息,需要先调用cmd.exe
    bat = 'cmd.exe /c "cd /d ' + dir + ' && dir"'
    stdin, stdout, stderr = ssh.exec_command(bat.encode("gbk"))

    # print('cmd.exe /c "cd ' + dir + ' && dir"')

    # 获取结果并对结果进行转码
    result = stdout.read().decode("GBK")
    # print(result)

    # 按换行符分割
    result = result.split('\n')

    print('在"' + dir + '"下找到日期为"' + date + '"的文件:')

    # 匹配规则:以xxxx/xx/xx开头的行
    # date_reg_exp = re.compile('\d{4}[-/]\d{2}[-/]\d{2}[\s\S]*')
    date_reg_exp = re.compile(date + '[\s\S]*')

    # 定义一个数组用来存放匹配成功的行
    cg = []
    bytes_sum = 0

    for i in range(len(result)):
        # 根据正则查找所有日期并返回
        matches_list = date_reg_exp.findall(result[i])

        # 列出并打印匹配的日期
        for match in matches_list:
            if match.find('DIR') == -1:
                print(match)
                cg.append(match)
                # 将每个文件的属性分割成数组,从分别是0、日期 1、时间 2、大小(bytes) 3、名称
                match = match.split()
                bytes_sum = bytes_sum + int(match[2].replace(',', ''))

    # 直接输出匹配成功的数组成员数
    print('一共找到\033[0;32m%s\033[0m' % str(len(cg)) + '个文件。')
    # for i in range(len(cg)):
    #    print(cg[i])

    if bytes_sum < 1024:  # 小于1kb
        bytes_sum = str(round(bytes_sum, 2)) + ' B'
    elif bytes_sum >= 1024 and bytes_sum < 1048576:
        bytes_sum = str(round(bytes_sum / 1024, 2)) + ' KB'
    elif bytes_sum >= 1048576 and bytes_sum < 1073741824:
        bytes_sum = str(round(bytes_sum / 1024 / 1024, 2)) + ' MB'
    elif bytes_sum >= 1073741824 and bytes_sum < 1099511627776:
        bytes_sum = str(round(bytes_sum / 1024 / 1024 / 1024, 2)) + ' GB'
    elif bytes_sum >= 1099511627776:
        bytes_sum = str(round(bytes_sum / 1024 / 1024 / 1024 / 1024, 2)) + ' TB'

    # 打印所有文件大小之和
    print('总大小:\033[0;32m%s\033[0m' % bytes_sum)

#函数:从配置文件中读取备份配置信息,将值传入到check_backup进行检查
def do_check(ssh):
    # 生成config对象
    conf = configparser.ConfigParser()

    # 获取文件的当前路径(绝对路径)
    cur_path = os.path.dirname(os.path.realpath(__file__))
    # print(cur_path)

    # 获取config.ini的路径
    config_path = os.path.join(cur_path, 'config.ini')
    # print(config_path)

    # 读取配置文件
    # conf.read(config_path)
    conf.read(config_path, encoding="utf-8-sig")

    # 以列表形式返回所有的section
    sections = conf.sections()
    # print('sections:', sections)

    len_sections = len(sections)
    print('正在检查备份情况...')
    # print('正在执行备份检查...')
    for i in range(len(sections)):
        print(sections[i])  # 每个节点的名称
        options = conf.options(sections[i])  # 获取每个节点下的所有配置项path、rate、num
        path = conf.get(sections[i], conf.options(sections[i])[0])  # 获取path的值
        # print('看后边:' + path.encode('utf-8').decode("utf-8"))
        rate = conf.get(sections[i], conf.options(sections[i])[1])  # 获取rate的值
        num = conf.get(sections[i], conf.options(sections[i])[2])  # 获取num的值
        print('path:' + path + ',rate:' + rate + ',num:' + num)
        # 获取今天是星期几
        day = datetime.now().weekday()  # 返回的是0-6是星期一到星期日

        # 获取今天的日期,格式YYYY/MM/DD
        today = datetime.now().strftime('%Y/%m/%d')

        if int(rate) < 0:
            print('前' + str(int(rate) * -1) + '天')
            check_day = (datetime.now() + timedelta(days=int(rate))).strftime('%Y/%m/%d')

        elif rate == '0':
            print('每天')
            check_day = today
        # print(check_day)
        # check_backup(path, check_day)
        elif rate == '1':
            print('星期一')
            if day == 0:
                check_day = today
            # print(check_day)
            # check_backup(path, check_day)
            else:
                check_day = get_previous_byday('Monday').strftime('%Y/%m/%d')
            # print(get_previous_byday('Monday').strftime('%Y/%m/%d'))
            # check_backup(path, check_day)

        elif rate == '2':
            print('星期二')
            if day == 1:
                check_day = today
            # print(check_day)
            else:
                check_day = get_previous_byday('Tuesday').strftime('%Y/%m/%d')
            # print(get_previous_byday('Tuesday').strftime('%Y/%m/%d'))
            # check_backup(path, check_day)

        elif rate == '3':
            print('星期三')
            if day == 2:
                check_day = today
            # print(check_day)
            # check_backup(path, check_day)
            else:
                check_day = get_previous_byday('Wednesday').strftime('%Y/%m/%d')
            # print(get_previous_byday('Wednesday').strftime('%Y/%m/%d'))
            # check_backup(path, check_day)

        elif rate == '4':
            print('星期四')
            if day == 3:
                check_day = today
            # print(check_day)
            # check_backup(path, check_day)
            else:
                check_day = get_previous_byday('Thursday').strftime('%Y/%m/%d')
            # print(get_previous_byday('Thursday').strftime('%Y/%m/%d'))
            # check_backup(path, check_day)

        elif rate == '5':
            print('星期五')
            if day == 4:
                check_day = today
            # print(check_day)
            # check_backup(path, check_day)
            else:
                check_day = get_previous_byday('Friday').strftime('%Y/%m/%d')
            # print(get_previous_byday('Friday').strftime('%Y/%m/%d'))
            # check_backup(path, check_day)

        elif rate == '6':
            print('星期六')
            if day == 5:
                check_day = today
            # print(check_day)
            # check_backup(path, check_day)
            else:
                check_day = get_previous_byday('Saturday').strftime('%Y/%m/%d')
            # print(get_previous_byday('Saturday').strftime('%Y/%m/%d'))
            # check_backup(path, check_day)

        elif rate == '7':
            print('星期天')
            if day == 6:
                check_day = today
            # print(check_day)
            # check_backup(path, check_day)
            else:
                check_day = get_previous_byday('Sunday').strftime('%Y/%m/%d')
            # print(get_previous_byday('Sunday').strftime('%Y/%m/%d'))
            # check_backup(path, check_day)

        else:
            print('非法rate值!')
        check_backup(ssh, path, check_day)

#查看备份的配置信息
def show_Config():
    # 生成config对象
    conf = configparser.ConfigParser()

    # 获取文件的当前路径(绝对路径)
    cur_path = os.path.dirname(os.path.realpath(__file__))
    # print(cur_path)

    # 获取config.ini的路径
    config_path = os.path.join(cur_path, 'config.ini')
    # print(config_path)

    # 读取配置文件
    # conf.read(config_path)
    conf.read(config_path, encoding="utf-8-sig")

    # 以列表形式返回所有的section
    sections = conf.sections()
    # print('sections:', sections)

    print('当前备份配置信息如下:')
    for i in range(len(sections)):
        # print(sections[i]) #每个节点的名称
        options = conf.options(sections[i])  # 获取每个节点下的所有配置项path、rate、num
        path = conf.get(sections[i], conf.options(sections[i])[0])  # 获取path的值
        # print('看后边:' + path.encode('utf-8').decode("utf-8"))
        rate = conf.get(sections[i], conf.options(sections[i])[1])  # 获取rate的值
        num = conf.get(sections[i], conf.options(sections[i])[2])  # 获取num的值
        print('节点名:' + sections[i] + ',' + '备份路径:' + path + ',备份频率:' + rate + ',文件数量:' + num)


# 增加备份的配置信息
def add_Config():
    # 生成config对象
    conf = configparser.ConfigParser()

    # 获取文件的当前路径(绝对路径)
    cur_path = os.path.dirname(os.path.realpath(__file__))
    # print(cur_path)

    # 获取config.ini的路径
    config_path = os.path.join(cur_path, 'config.ini')
    # print(config_path)

    # 读取配置文件
    # conf.read(config_path)
    conf.read(config_path, encoding="utf-8-sig")
    while True:
        # conf.add_section('sec_1')
        # conf.set('sec_1', 'path', 'M:\ORACLE_EXP_EXPDP\ORACLE_EXP_EXPDP')
        # conf.set('sec_1', 'rate', '0')
        # conf.set('sec_1', 'num', '60')
        section = input("请输入新的[节点名],输入q/Q可退出:")
        if section == 'q':
            break
        path = input("请输入新的[备份路径],输入q/Q可退出:")
        if path == 'q':
            break
        rate = input("请输入新的[备份频率],输入q/Q可退出:")
        if rate == 'q':
            break
        num = input("请输入新的[文件数量],输入q/Q可退出:")
        if num == 'q':
            break

        try:
            conf.add_section(section)
            conf.set(section, 'path', path)
            conf.set(section, 'rate', rate)
            conf.set(section, 'num', num)

        # except DuplicateSectionError:
        except Exception as e:
            # print("Section '" + section + "' already exists")
            print(e)
            continue
        else:
            # 写回配置文件
            print('添加成功!')
            conf.write(open("config.ini", mode='w', encoding='utf-8'))
            # show_Config()
            # continue
            break


# 删除备份的配置信息
def delete_Config():
    # 生成config对象
    conf = configparser.ConfigParser()

    # 获取文件的当前路径(绝对路径)
    cur_path = os.path.dirname(os.path.realpath(__file__))
    # print(cur_path)

    # 获取config.ini的路径
    config_path = os.path.join(cur_path, 'config.ini')
    # print(config_path)

    # 读取配置文件
    # conf.read(config_path)
    conf.read(config_path, encoding="utf-8-sig")
    while True:
        # conf.add_section('sec_1')
        # conf.set('sec_1', 'path', 'M:\ORACLE_EXP_EXPDP\ORACLE_EXP_EXPDP')
        # conf.set('sec_1', 'rate', '0')
        # conf.set('sec_1', 'num', '60')
        section = input("请选择需要删除的[节点名],输入q/Q可退出:")
        if section == 'q':
            break

        try:
            conf.remove_section(section)

        # except DuplicateSectionError:
        except Exception as e:
            # print("Section '" + section + "' already exists")
            print(e)
        else:
            # 写回配置文件
            print('删除成功!')
            conf.write(open("config.ini", mode='w', encoding='utf-8'))
            # continue
            break


# 修改备份的配置信息
def update_Config():
    # 生成config对象
    conf = configparser.ConfigParser()

    # 获取文件的当前路径(绝对路径)
    cur_path = os.path.dirname(os.path.realpath(__file__))
    # print(cur_path)

    # 获取config.ini的路径
    config_path = os.path.join(cur_path, 'config.ini')
    # print(config_path)

    # 读取配置文件
    # conf.read(config_path)
    conf.read(config_path, encoding="utf-8-sig")
    while True:
        # conf.add_section('sec_1')
        # conf.set('sec_1', 'path', 'M:\ORACLE_EXP_EXPDP\ORACLE_EXP_EXPDP')
        # conf.set('sec_1', 'rate', '0')
        # conf.set('sec_1', 'num', '60')
        section = input("请选择需要修改的[节点名],输入q/Q可退出:")
        if section == 'q':
            break
        path = input("请输入新的[备份路径],输入q/Q可退出:")
        if path == 'q':
            break
        rate = input("请输入新的[备份频率],输入q/Q可退出:")
        if rate == 'q':
            break
        num = input("请输入新的[文件数量],输入q/Q可退出:")
        if num == 'q':
            break

        try:
            conf.set(section, 'path', path)
            conf.set(section, 'rate', rate)
            conf.set(section, 'num', num)

        except Exception as e:
            # print("Section '" + section + "' already exists")
            print(e)
        else:
            # 写回配置文件
            print('修改成功!')
            conf.write(open("config.ini", mode='w', encoding='utf-8'))
            # continue
            break

if __name__ == '__main__':
    print('欢迎使用远程检查工具')
    nowTime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')  # 现在
    print('现在是:' + nowTime)


    while True:
        print('~~~~~~菜单~~~~~~')
        print('1、查看配置信息')
        print('2、增加配置信息')
        print('3、删除配置信息')
        print('4、修改配置信息')
        print('5、检查备份情况')
        print('(回复q/Q可退出程序)')
        choice = input('请选择:')
        print(choice)
        if choice == '1':
            show_Config()
        elif choice == '2':
            show_Config()
            add_Config()
        elif choice == '3':
            show_Config()
            delete_Config()
        elif choice == '4':
            show_Config()
            update_Config()
        elif choice == '5':
            s = get_Connect()
            do_check(s)
            close_Connect(s)
        elif choice == 'q' or choice == 'Q':
            exit(100)
        else:
            print('输入有误,请重新输入!')

    # 结束
    print('再见!')

你可能感兴趣的:(python)