作者:天使犯罪de快乐 | 来源:互联网 | 2023-10-13 08:33
用于将终端证书文件批量导入进数据库
【注意】Python2和Python3,在数的进制转换上,不太一样
Python 2
content_str += binascii.hexlify(b)
Python 3
content_str += hex(b)[2:].zfill(2)
完整源码如下:
import os
import logging
import binascii
cert_file_base = 'E:/test/PycharmProjects/ImportCert'
sql_file_name = 'import_cert.sql'
def get_rtu_list():rtu_list = []try:with open('rtu_id_list.txt', 'r') as rtu_file:rtu_ids = rtu_file.readlines()for i in range(0, len(rtu_ids)):rtu_list.append(rtu_ids[i].strip())except IOError as err:logging.error('[Error] when read rtu_id_list.txt: %s', err)finally:return rtu_list
def get_cert_file(rtu_list):for rtu_id in rtu_list:cert_file_dir = cert_file_base + '/' + rtu_idtry:cert_file_list = os.listdir(cert_file_dir)except OSError as err:logging.error('[Error] when read %s: %s', cert_file_dir, err)continueif len(cert_file_list) != 1:logging.error("[Error] There be %d files in path: %s", len(cert_file_list), cert_file_dir)continueelse:print_sql(rtu_id, cert_file_dir, cert_file_list[0])
def print_sql(rtu_id, cert_file_dir, cert_file_name):cert_file_path = cert_file_dir + "/" + cert_file_nametry:with open(cert_file_path, 'rb') as cert_file:content_bin = cert_file.read()except IOError as err:logging.error('[Error] when read %s: %s', cert_file_path, err)content_str = ''for b in content_bin:content_str += binascii.hexlify(b) content_str += ' 'sql = "insert into fes_cert(rtu_id,cert_file_name,cert_content) " \"values(" + rtu_id + ",'" + cert_file_name + "','" + content_str.strip() + "'); "logging.info(sql)
def clean_thing(file_name):try:file = open(file_name, 'w').close()except IOError as err:logging.error('[Error] when clean %s: %s', file_name, err)if __name__ == '__main__':clean_thing(sql_file_name)logging.basicConfig(level=logging.DEBUG, filename=sql_file_name, filemode='a', format='%(message)s')get_cert_file(get_rtu_list())