Windows環境でpythonでリモートサーバのバックアップファイルのチェックを実現
15964 ワード
# -*- 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('
')
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(' !')