基于Python实现GIT上传敏感信息预扫描工具

来源:互联网 发布:shell编程视频教程 编辑:程序博客网 时间:2024/06/07 03:25

前言

有关GIT泄露信息的安全问题频出,目前市面上大部分敏感信息扫描工具都是针对GITHUB平台上已上传的代码进行批量扫描,缺乏针对上传前代码进行扫描的工具。因此我用Python实现了一个小型的扫描工具,仅仅支持对敏感信息的替换和恢复。代替手工对小型项目的敏感信息进行替换和恢复操作。

思路与代码

实现思路很简单,就是文本扫描和替换。

#Python敏感信息扫描工具import osfile_list=[]dir_list=[]wrong_messages=['123456']    #敏感信息列表log_path='d:/log.txt'       #日志地址print('请输入扫描路径')def search(path):    for d in os.listdir(path):        file_path=os.path.join(path, str(d))        if os.path.isfile(file_path) and str(file_path).__contains__('.py'):            with open(file_path,'r') as f:                codes = f.readlines()            with open(file_path,'w') as f:                with open(log_path,'a') as log:                    for code in codes:                        for wrong_message in wrong_messages:                            if code.__contains__(wrong_message): #如果包含敏感信息                                log.write('操作文件:'+file_path+'\n')                                log.write('操作行数:' + str(codes.index(code))+'\n')                                log.write('操作位置:'+str(code.index(wrong_message))+'\n')                                log.write('删除内容:'+wrong_message+'\n')                                f.write(code.replace(wrong_message,'')) #替换敏感信息                            else:                                f.write(code)        elif os.path.isdir(file_path):            search(file_path)if __name__ == '__main__':    path = input()    search(path)

恢复工具的思想就是解析日志文件,按照日志文件信息进行恢复。

#恢复清除的敏感信息import oslog_path='d:/log.txt'       #日志地址with open(log_path,'r') as log_file:    logs=log_file.readlines()    i=0    while i<len(logs):        path=logs[i].replace('操作文件:','').replace('\\','/').replace('\n','')        linenum=int(logs[i+1].replace('操作行数:','').replace('\n',''))        pos=int(logs[i+2].replace('操作位置:','').replace('\n',''))        content=logs[i+3].replace('删除内容:','').replace('\n','')        with open(path,'r') as f:            lines = f.readlines()        with open(path,'w') as f:            num=0            for line in lines:          #根据LOG恢复代码信息                if num==linenum:                    linelist=list(line)                    line=''.join(linelist[0:pos]+list(content)+linelist[pos:len(line)-1])                    f.write(line+'\n')                else:                    f.write(line)                num+=1        i+=4with open(log_path,'w') as log_file:    #清空LOG    log_file.write('')
原创粉丝点击