#!/bin/env python
# -*- coding: utf-8 -*-
import datetime
import os
import fileinput
import psycopg2
import tarfile
import shutil
import logging
import time
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', # 日志格式
datefmt='%Y-%m-%d %H:%M:%S', # 时间格式:2018-11-12 23:50:21
filename='/home/hjpt/App/hplatform/logs/hplatform_local_scan_del_lsms.log', # 日志的输出路径
filemode='a')
#获取目录下的所有文件
def scan_file(infor):
tar_file = []
remote_path = infor[1]
for files in os.listdir(remote_path):
print files
file_name = remote_path + '/' + files
print file_name
if os.path.splitext(file_name)[1] == '.gz':
tar_file.append(files)
print tar_file
return tar_file
#删除文件的第一行
def del_file_first(del_file):
for line in fileinput.input(del_file, inplace=1):
if not fileinput.isfirstline():
print line.replace("\n","")
#解压缩模块
def un_tar(file_names):
un_tar_file = []
ufile = tarfile.open(file_names)
names = ufile.getnames()
for tt in names:
ufile.extract(tt, path=remote_path)
un_tar_file.append(tt)
print un_tar_file
ufile.close()
return un_tar_file
if __name__ == '__main__':
sql = '''
SELECT
scan_group_id,
remote_path,
remote_bk_path,
local_path,
file_regular,
chkf_regular,
mv_flag,
data_source,
table_attr,
prov_id
FROM
public.conf_path_info
WHERE
is_valid = '0' and scan_group_id = 'XXXX'
'''
try:
pg_conn = psycopg2.connect(database='XX', user='XX', password='XXXX', host='XXXX', port='XXXX')
cur = pg_conn.cursor()
cur.execute(sql)
rows = cur.fetchall()
print(rows)
pg_conn.close()
except Exception as e:
print e
else:
while True:
for i in rows:
remote_path = i[1]
remote_bk_path = i[2]
local_path = i[3]
files = scan_file(i)
#获取压缩文件名称
for filename in files:
print filename
file = remote_path + '/' + filename
bak_file = remote_bk_path + '/' + filename
try:
if os.path.getsize(file) == 0:
os.remove(file)
logging.info(file + 'file size is : 0 ,delete from local.')
else:
sss = os.path.getsize(file)
#解压压缩文件
un_tar_file=un_tar(file)
logging.info(file + 'file size is :' + str(sss) + ': untar file successful !')
#将文件从正式目录挪到bak目录
shutil.move(file,bak_file)
for unfilename in un_tar_file:
dfilename = remote_path + '/' + unfilename
tmpfilename = local_path + '/' + unfilename
#删除文件的第一行
del_file_first(dfilename)
logging.info(dfilename + 'delete first line successful !')
shutil.move(dfilename,tmpfilename)
del un_tar_file[0]
except Exception as e:
print e