def main(f, k): print("[*] generating ICE key for build: %d" % (k)) key = b'CSGO' key += bytes([((k) & 0xff)]) key += bytes([((k >> 8) & 0xff)]) key += bytes([((k >> 16) & 0xff)]) key += bytes([((k >> 24) & 0xff)]) key += bytes([((k >> 2) & 0xff)]) key += bytes([((k >> 10) & 0xff)]) key += bytes([((k >> 18) & 0xff)]) key += bytes([((k >> 26) & 0xff)]) key += bytes([((k >> 4) & 0xff)]) key += bytes([((k >> 12) & 0xff)]) key += bytes([((k >> 20) & 0xff)]) key += bytes([((k >> 28) & 0xff)]) print("[*] done") print("[*] generating pattern") cmp = [] test = [ord(x) for x in 'ALLES{'] for _ in range(8): cmp.append(bytes(test[1:-1])) test = bit_shift_array_right(test, 1) print("[*] reading packets") with open(f, "rb") as f_: for _, pkt in Reader(f_): eth = Ethernet(pkt) ip = eth.data udp = ip.data payload = udp.data if consume(payload, key, cmp): break print("[*] done")
def analyse_receiver_dump(self, flow, senderIp): bytes = 0 packets = 0 progress = ProgressBar("receiver dump", os.stat(self.senderDumps[flow]).st_size) try: with open(self.receiverDumps[flow], 'rb') as dump: for timestamp, packet in Reader(dump): size = len(packet) ip = Ethernet(packet).data if ip.src == senderIp: self.process_receiver_sent_packet( flow, timestamp, size, ip) self.receiverSentBytes[flow] += size self.receiverSentPkts[flow] += 1 bytes += size packets += 1 progress.update(bytes) except IOError as error: raise AnalysisError("Failed to read dump %s:\n%s" % (self.receiverDumps[flow], error)) progress.finish() print("Total: %d pkts/%d bytes, from sender: %d pkts/%d bytes\n" % (packets, bytes, self.receiverSentPkts[flow], self.receiverSentBytes[flow]))
def shark(file): """ Parse pcap (tcpdump) to extract networking info and CA commands. This function is also accessible via a CLI installed with caproto. Example:: sudo tcpdump -w - | caproto-shark Parameters ---------- file : buffer Yields ------ command_context : SimpleNamespace Contains timestamp, ethernet, src, dst, ip, transport, and command. """ banned = set() for timestamp, buffer in Reader(file): ethernet = Ethernet(buffer) ip = ethernet.data if not isinstance(ip, IP): continue transport = ip.data if not isinstance(transport, (TCP, UDP)): continue try: src = inet_ntoa(ip.src) dst = inet_ntoa(ip.dst) if isinstance(transport, TCP): if (ip.src, transport.sport) in banned: continue data = bytearray(transport.data) while True: data, command, _ = read_from_bytestream(data) if command is NEED_DATA: break yield SimpleNamespace(timestamp=timestamp, ethernet=ethernet, src=src, dst=dst, ip=ip, transport=transport, command=command) elif isinstance(transport, UDP): if (ip.src, transport.sport) in banned: continue address = inet_ntoa(ip.src) for command in read_datagram(transport.data, address): yield SimpleNamespace(timestamp=timestamp, ethernet=ethernet, src=src, dst=dst, ip=ip, transport=transport, command=command) except ValidationError: banned.add((ip.src, transport.sport))
def get_sender_ip(self, flow): senderIp = None for dumpPath in [self.senderDumps[flow], self.receiverDumps[flow]]: try: with open(dumpPath, 'rb') as dumpFile: reader = Reader(dumpFile) try: packet = next(iter(reader))[1] ip = Ethernet(packet).data leftIp = min(ip.src, ip.dst) rightIp = max(ip.src, ip.dst) senderIp = leftIp if self.directions[ flow] == RIGHTWARD else rightIp break # switch to the next flow except StopIteration: pass except IOError as error: raise AnalysisError("Failed to read dump %s:\n%s" % (dumpPath, error)) return senderIp
def xDPIsession(scan_path): data = [] try: from datetime import datetime from dpkt.pcap import Reader from dpkt.ethernet import Ethernet from socket import inet_ntoa with open(scan_path, 'rb') as pf: dpkt_file_object = False try: dpkt_file_object = Reader(pf) except Exception as err: dpkt_file_object = False #print("[-] pcap corruption detected : {}".format(pcap_path)) if dpkt_file_object: #print("[+] pcap's health fine : {}".format(pcap_path)) for ts, payload in dpkt_file_object: t1, p = ts, payload t = datetime.fromtimestamp(t1).strftime( "%Y-%m-%d %H:%M:%S") eth = False try: eth = Ethernet(payload) except: eth = False if eth: if eth.type == 2048: ip = eth.data src_ip = inet_ntoa(ip.src) dst_ip = inet_ntoa(ip.dst) data.append({ 'src_ip': src_ip, 'dst_ip': dst_ip, }) except Exception as err: print(err) return data
def get_base_time(self): minBaseTime = None for flow in range(0, self.flows): for dumpPath in [self.senderDumps[flow], self.receiverDumps[flow]]: try: with open(dumpPath, 'rb') as dumpFile: reader = Reader(dumpFile) try: baseTime = next(iter(reader))[0] if minBaseTime is None: minBaseTime = baseTime else: minBaseTime = min(minBaseTime, baseTime) except StopIteration: pass except IOError as error: raise AnalysisError("Failed to read dump %s:\n%s" % (dumpPath, error)) return minBaseTime
def passiveSession(pcap_path): data = {'healthy_sessions': [], 'corrupt_sessions': []} sessions = {} complete = [] with open(pcap_path, 'rb') as pf: pcap_file_name = pcap_path dpkt_file_object = False try: dpkt_file_object = Reader(pf) except Exception as err: dpkt_file_object = False print("[-] pcap corruption detected : {}".format(pcap_path)) if dpkt_file_object: print("[+] pcap's health fine : {}".format(pcap_path)) for ts, payload in dpkt_file_object: t1, p = ts, payload t = datetime.fromtimestamp(t1).strftime("%Y-%m-%d %H:%M:%S") eth = False try: eth = Ethernet(payload) except: eth = False if eth: if eth.type == 2048: ip = eth.data src_ip = inet_ntoa(ip.src) dst_ip = inet_ntoa(ip.dst) if ip.p == 6: tcp_pkt_header = False tcp = ip.data try: tcp_pkt_header = tcp.__hdr__ except: tcp_pkt_header = False if tcp_pkt_header: tcp_packet_data = {} tcp_packet_data[ 'pcap_file_name'] = pcap_path.split( os.sep)[-1] tcp_packet_data['src_ip'], tcp_packet_data[ 'dst_ip'], tcp_packet_data[ 'pkts_num'] = src_ip, dst_ip, 1 tcp_src_port, tcp_dst_port = tcp.sport, tcp.dport tcp_packet_data['src_port'], tcp_packet_data[ 'dst_port'] = tcp_src_port, tcp_dst_port flags = flagScanner(tcp) tcp_packet_data[ 'pkts_size'] = tcp.data.__len__() uni_key = '{}{}{}{}'.format( tcp_packet_data['src_ip'], tcp_packet_data['src_port'], tcp_packet_data['dst_ip'], tcp_packet_data['dst_port']) if 'syn' in flags: if uni_key in sessions: del sessions[uni_key] tcp_packet_data['start_time'] = t tcp_packet_data['end_time'] = t tcp_packet_data['session'] = False tcp_packet_data['dns_data'] = False #if tcp_packet_data['src_ip'] in domains: # tcp_packet_data['dns_data'] = domains[tcp_packet_data['src_ip']] #if tcp_packet_data['dst_ip'] in domains: # tcp_packet_data['dns_data'] = domains[tcp_packet_data['dst_ip']] sessions[uni_key] = tcp_packet_data elif 'fin' in flags: if uni_key in sessions: sessions[uni_key][ 'pkts_num'] += tcp_packet_data[ 'pkts_num'] sessions[uni_key][ 'pkts_size'] += tcp_packet_data[ 'pkts_size'] sessions[uni_key]['session'] = True sessions[uni_key]['end_time'] = t complete_session = sessions[uni_key] data["healthy_sessions"].append( complete_session) del sessions[uni_key] else: if uni_key in sessions: sessions[uni_key][ 'pkts_num'] += tcp_packet_data[ 'pkts_num'] sessions[uni_key][ 'pkts_size'] += tcp_packet_data[ 'pkts_size'] sessions[uni_key]['end_time'] = t for session in sessions: data['corrupt_sessions'].append(sessions[session]) return data
def passiveDns(pcap_path): data = {'dns_requests': [], 'dns_responses': []} sessions = {} complete = [] with open(pcap_path, 'rb') as pf: pcap_file_name = pcap_path dpkt_file_object = False try: dpkt_file_object = Reader(pf) except Exception as err: dpkt_file_object = False print("[-] pcap corruption detected : {}".format(pcap_path)) if dpkt_file_object: print("[+] pcap's health fine : {}".format(pcap_path)) for ts, payload in dpkt_file_object: t1, p = ts, payload t = datetime.fromtimestamp(t1).strftime("%Y-%m-%d %H:%M:%S") eth = False try: eth = Ethernet(payload) except: eth = False if eth: if eth.type == 2048: ip = eth.data src_ip = inet_ntoa(ip.src) dst_ip = inet_ntoa(ip.dst) if ip.p == 17: udp_pkt_header = False udp = ip.data try: udp_pkt_header = udp.__hdr__ except: udp_pkt_header = False if udp_pkt_header: udp_src_port, udp_dst_port = udp.sport, udp.dport if udp_src_port == 53: dns_response_data = DnsResponseParser(udp) dns_response_data[ 'src_ip'], dns_response_data[ 'dst_ip'] = src_ip, dst_ip dns_response_data[ 'src_port'], dns_response_data[ 'dst_port'] = udp_src_port, udp_dst_port dns_response_data['dns_time'] = t #dns_response_data['upload_id'] = upload_id data['dns_responses'].append( dns_response_data) elif udp_dst_port == 53: dns_request_data = DnsRequestParser(udp) dns_request_data[ 'src_ip'], dns_request_data[ 'dst_ip'] = src_ip, dst_ip dns_request_data[ 'src_port'], dns_request_data[ 'dst_port'] = udp_src_port, udp_dst_port dns_request_data['dns_time'] = t #dns_request_data['upload_id'] = upload_id data['dns_requests'].append( dns_request_data) return data
def PacketDiessector(pcap_path, upload_id): def flagScanner(tcp): result = [] if (tcp.flags & TH_FIN) != 0: result.append('fin') if (tcp.flags & TH_SYN) != 0: result.append('syn') if (tcp.flags & TH_RST) != 0: result.append('rst') if (tcp.flags & TH_PUSH) != 0: result.append('psh') if (tcp.flags & TH_ACK) != 0: result.append('ack') if (tcp.flags & TH_URG) != 0: result.append('urg') if (tcp.flags & TH_ECE) != 0: result.append('ece') if (tcp.flags & TH_CWR) != 0: result.append('cwr') return result #print("[+] scanning : {}".format(pcap_path)) domains = {} sessions = {} complete = [] #incomplete = [] with open(pcap_path, 'rb') as pf: pcap_file_name = pcap_path dpkt_file_object = False try: dpkt_file_object = Reader(pf) except Exception as err: dpkt_file_object = False #print("[-] pcap corruption detected : {}".format(pcap_path)) if dpkt_file_object: #print("[+] pcap's health fine : {}".format(pcap_path)) for ts, payload in dpkt_file_object: t1, p = ts, payload t = datetime.fromtimestamp(t1).strftime("%Y-%m-%d %H:%M:%S") eth = False try: eth = Ethernet(payload) except: eth = False if eth: if eth.type == 2048: ip = eth.data src_ip = inet_ntoa(ip.src) dst_ip = inet_ntoa(ip.dst) if ip.p == 17: udp_pkt_header = False udp = ip.data try: udp_pkt_header = udp.__hdr__ except: udp_pkt_header = False if udp_pkt_header: udp_src_port, udp_dst_port = udp.sport, udp.dport if udp_src_port == 53: dns_response_data = DnsResponseParser(udp) dns_response_data[ 'src_ip'], dns_response_data[ 'dst_ip'] = src_ip, dst_ip dns_response_data[ 'src_port'], dns_response_data[ 'dst_port'] = udp_src_port, udp_dst_port dns_response_data['dns_time'] = t dns_response_data['upload_id'] = upload_id domains[dst_ip] = dns_response_data elif udp_dst_port == 53: dns_request_data = DnsRequestParser(udp) dns_request_data[ 'src_ip'], dns_request_data[ 'dst_ip'] = src_ip, dst_ip dns_request_data[ 'src_port'], dns_request_data[ 'dst_port'] = udp_src_port, udp_dst_port dns_request_data['dns_time'] = t dns_request_data['upload_id'] = upload_id domains[src_ip] = dns_request_data elif ip.p == 6: tcp_pkt_header = False tcp = ip.data try: tcp_pkt_header = udp.__hdr__ except: tcp_pkt_header = False if tcp_pkt_header: tcp_packet_data = {} tcp_packet_data['upload_id'] = upload_id tcp_packet_data[ 'pcap_file_path'] = pcap_file_name.split( 'media')[-1] tcp_packet_data['src_ip'], tcp_packet_data[ 'dst_ip'], tcp_packet_data[ 'pkts_num'] = src_ip, dst_ip, 1 tcp_src_port, tcp_dst_port = tcp.sport, tcp.dport tcp_packet_data['src_port'], tcp_packet_data[ 'dst_port'] = tcp_src_port, tcp_dst_port flags = flagScanner(tcp) tcp_packet_data[ 'pkts_size'] = tcp.data.__len__() uni_key = '{}{}{}{}'.format( tcp_packet_data['src_ip'], tcp_packet_data['src_port'], tcp_packet_data['dst_ip'], tcp_packet_data['dst_port']) if 'syn' in flags: if uni_key in sessions: del sessions[uni_key] tcp_packet_data['start_time'] = t tcp_packet_data['end_time'] = t tcp_packet_data['session'] = False tcp_packet_data['dns_data'] = False if tcp_packet_data['src_ip'] in domains: tcp_packet_data['dns_data'] = domains[ tcp_packet_data['src_ip']] if tcp_packet_data['dst_ip'] in domains: tcp_packet_data['dns_data'] = domains[ tcp_packet_data['dst_ip']] sessions[uni_key] = tcp_packet_data elif 'fin' in flags: if uni_key in sessions: sessions[uni_key][ 'pkts_num'] += tcp_packet_data[ 'pkts_num'] sessions[uni_key][ 'pkts_size'] += tcp_packet_data[ 'pkts_size'] sessions[uni_key]['session'] = True sessions[uni_key]['end_time'] = t complete_session = sessions[uni_key] complete.append(complete_session) del sessions[uni_key] else: if uni_key in sessions: sessions[uni_key][ 'pkts_num'] += tcp_packet_data[ 'pkts_num'] sessions[uni_key][ 'pkts_size'] += tcp_packet_data[ 'pkts_size'] sessions[uni_key]['end_time'] = t for session in sessions: complete.append(sessions[session]) for sess in complete: # phase one scan sess['phase_one_scan'] = False detected_subnets = [] src_subnets = all_matching_cidrs(sess['src_ip'], subnets) dst_subnets = all_matching_cidrs(sess['dst_ip'], subnets) if src_subnets: detected_subnets.append(str(src_subnets[0])) if dst_subnets: detected_subnets.append(str(dst_subnets[0])) if detected_subnets: detected_subnet = detected_subnets[0] sess['phase_one_scan'] = subnet_config.loc[ subnet_config['subnet'] == detected_subnet].to_dict() ddf = subnet_config.loc[subnet_config['subnet'] == detected_subnet].to_dict() sess['phase_one_scan'] = { 'subnet': list(ddf['subnet'].values())[0].strip(), 'application': list(ddf['application'].values())[0].strip(), 'activity': list(ddf['activity'].values())[0].strip(), 'category': list(ddf['category'].values())[0].strip() } # phase two scan sess['phase_two_scan'] = False if sess['dns_data']: sess['phase_two_scan'] = False detected_dnss = [] if 'domain' in sess['dns_data']: domain = sess['dns_data']['domain'] for item in dns_list: if item in domain: detected_dnss.append(item.strip()) if detected_dnss: df = dns_config.loc[dns_config['domain'] == detected_dnss[0]].to_dict() sess['phase_two_scan'] = { 'domain': list(df['domain'].values())[0].strip(), 'application': list(df['application'].values())[0].strip(), 'activity': list(df['activity'].values())[0].strip(), 'category': list(df['category'].values())[0].strip() } sess['hash'] = hashlib.md5(str( sess.values()).encode('utf-8')).hexdigest() return complete
def PacketDiessector(pcap_path): def flagScanner(tcp): result = [] if (tcp.flags & TH_FIN) != 0: result.append('fin') if (tcp.flags & TH_SYN) != 0: result.append('syn') if (tcp.flags & TH_RST) != 0: result.append('rst') if (tcp.flags & TH_PUSH) != 0: result.append('psh') if (tcp.flags & TH_ACK) != 0: result.append('ack') if (tcp.flags & TH_URG) != 0: result.append('urg') if (tcp.flags & TH_ECE) != 0: result.append('ece') if (tcp.flags & TH_CWR) != 0: result.append('cwr') return result print "[+] scanning : {}".format(pcap_path) sessions = {} d = {} for ts, payload in Reader(open(pcap_path, 'rb')): t, p = ts, payload eth = Ethernet(payload.__str__()) packet = {} if eth.type == ETH_TYPE_IP: ip = eth.data packet['source_ip'] = inet_ntoa(ip.src) packet['destination_ip'] = inet_ntoa(ip.dst) if ip.p == IP_PROTO_TCP: tcp = ip.data if tcp.dport == 25: packet['source_port'] = tcp.sport packet['destination_port'] = tcp.dport packet['flags'] = flagScanner(tcp) packet['pkts_num'] = 1 packet['pkts_size'] = tcp.data.__len__() packet['data'] = tcp.data uni_key = '{}:{}-->{}:{}'.format( packet['source_ip'], packet['source_port'], packet['destination_ip'], packet['destination_port']) if 'syn' in packet['flags']: if uni_key in sessions: del sessions[uni_key] sessions[uni_key] = packet elif 'fin' in packet['flags']: if uni_key in sessions: #sessions[uni_key]['flags'].extend(packet['flags']) #sessions[uni_key]['pkts_num']+=packet['pkts_num'] #sessions[uni_key]['pkts_size']+=packet['pkts_size'] sessions[uni_key]['source_port'] += packet[ 'source_port'] sessions[uni_key]['destination_port'] += packet[ 'destination_port'] sessions[uni_key]['data'] += packet['data'] complete_session = sessions[uni_key] body = complete_session['data'] port_source = complete_session['source_port'] port_dest = complete_session['destination_port'] sd = str(inet_ntoa(ip.src)) + ':' + str( port_source) + '-->' + inet_ntoa( ip.dst) + ': ' + str(port_dest) if 'AUTH PLAIN' in complete_session['data']: pass j = complete_session['data'][ complete_session['data'].find('AUTH PLAIN' ):200] dump(j, sd) #print '*'*50 if 'AUTH LOGIN' in complete_session['data']: pass k = complete_session['data'][ complete_session['data'].find('AUTH LOGIN' ):200] #print k #print k dump(k, sd) #print '*'*50 else: if uni_key in sessions: #sessions[uni_key]['flags'].extend(packet['flags']) #sessions[uni_key]['pkts_num']+=packet['pkts_num'] #sessions[uni_key]['pkts_size']+=packet['pkts_size'] sessions[uni_key]['source_port'] += packet[ 'source_port'] sessions[uni_key]['destination_port'] += packet[ 'destination_port'] sessions[uni_key]['data'] += packet['data']
def read_packets(cls, pcap_bytes): packet_data = {} fdesc = io.BytesIO(pcap_bytes) pcap = Reader(fdesc) pkt_data = [(k,Ether(v)) for k,v in pcap.readpkts()] return pkt_data
def PacketDiessector(pcap_path): final = {} count = 0 def parse_http(alll, sd): u, p = '', '' body = alll['data'] user = '' passwd = '' method = [ 'GET', 'POST', 'HEAD', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'TRACE' ] matched_lines = [line for line in body.split('\n') if "Host:" in line] host = '' if matched_lines: host = matched_lines[0] userfields = [ 'login', 'user', 'user_name', 'email', 'username', '_username', 'userid', 'form_loginname', 'loginname', 'login_id', 'loginid', 'user_id', 'member', 'mailaddress', 'membername', 'login_username', 'login_email', 'loginusername', 'loginemail', 'sign-in' ] passfields = [ 'pass', 'password', '_password', 'passwd', 'login_password', 'loginpassword', 'form_pw', 'userpassword', 'login_password' 'passwort', 'passwrd' ] for login in userfields: login_re = re.search('(%s=[^&]+)' % login, body, re.IGNORECASE) if login_re: user = login_re.group() for passfield in passfields: pass_re = re.search('(%s=[^&]+)' % passfield, body, re.IGNORECASE) if pass_re: passwd = pass_re.group() if user and passwd: u, p = user, passwd if 'Authorization: Basic' in body: k = body.split('\r\n') m = [] for item in k: if "Authorization: Basic" in item: user_id, password = base64.b64decode( str(item.split("Authorization: Basic"))).split(':') u, p = user_id, password # print_credentials(user_id,password,sd,host) if u: if p: uni = "{}{}{}".format(sd, u, p) final[uni] = { 'UserName': u.strip(':').strip().split(';')[0], 'Password': p.strip(':').strip().split(';')[0], 'Source_IP': alll['source_ip'], 'Destination_IP': alll['destination_ip'], 'Source_Port': str(alll['source_port']), 'Destination_Port': str(alll['destination_port']), 'Host': host.strip('\r').strip('Host:').strip(), 'Type': 'HTTP' } def flagScanner(tcp): result = [] if (tcp.flags & TH_FIN) != 0: result.append('fin') if (tcp.flags & TH_SYN) != 0: result.append('syn') if (tcp.flags & TH_RST) != 0: result.append('rst') if (tcp.flags & TH_PUSH) != 0: result.append('psh') if (tcp.flags & TH_ACK) != 0: result.append('ack') if (tcp.flags & TH_URG) != 0: result.append('urg') if (tcp.flags & TH_ECE) != 0: result.append('ece') if (tcp.flags & TH_CWR) != 0: result.append('cwr') return result "[+] scanning : {}".format(pcap_path) sessions = {} for ts, payload in Reader(open(pcap_path, "rb")): count += 1 print '>>> packets scanned - ', count, '\r', t, p = ts, payload try: eth = Ethernet(payload.__str__()) packet = {} if eth.type == ETH_TYPE_IP: ip = eth.data if type(ip) == str: continue packet['source_ip'] = inet_ntoa(ip.src) packet['destination_ip'] = inet_ntoa(ip.dst) if ip.p == IP_PROTO_TCP: tcp = ip.data try: if tcp.dport == 80 or tcp.sport == 80: packet['source_port'] = tcp.sport packet['destination_port'] = tcp.dport packet['flags'] = flagScanner(tcp) packet['pkts_num'] = 1 packet['pkts_size'] = tcp.data.__len__() packet['data'] = tcp.data uni_key = '{}:{}-->{}:{}'.format( packet['source_ip'], packet['source_port'], packet['destination_ip'], packet['destination_port']) if 'syn' in packet['flags']: if uni_key in sessions: del sessions[uni_key] sessions[uni_key] = packet elif 'fin' in packet['flags']: if uni_key in sessions: # sessions[uni_key]['flags'].extend(packet['flags']) # sessions[uni_key]['pkts_num']+=packet['pkts_num'] # sessions[uni_key]['pkts_size']+=packet['pkts_size'] sessions[uni_key]['source_port'] += packet[ 'source_port'] sessions[uni_key][ 'destination_port'] += packet[ 'destination_port'] sessions[uni_key]['data'] += packet['data'] complete_session = sessions[uni_key] # bodyy=complete_session['data'] port_source = complete_session[ 'source_port'] port_dest = complete_session[ 'destination_port'] parse_http(complete_session, uni_key) else: if uni_key in sessions: # sessions[uni_key]['flags'].extend(packet['flags']) # sessions[uni_key]['pkts_num']+=packet['pkts_num'] # sessions[uni_key]['pkts_size']+=packet['pkts_size'] sessions[uni_key]['source_port'] += packet[ 'source_port'] sessions[uni_key][ 'destination_port'] += packet[ 'destination_port'] sessions[uni_key]['data'] += packet['data'] except AttributeError: continue except dpkt.NeedData: print 'courpt packet' for item in final: pprint(final[item]) url_path = os.path.join(os.getcwd(), 'http_cred') if not os.path.exists(url_path): os.makedirs(url_path) f_name = 'http_cred' + '_' + datetime.datetime.now().__str__().replace( ' ', '_').replace(':', '-').replace('.', '-') + '.json' with open(os.path.join(url_path, f_name), 'w') as mu: mu.write(json.dumps([final[item]], encoding='latin1'))