Best Python code snippet using tempest_python
Server.py
Source:Server.py  
1"""2Rashmi Dodeja3Sandhya Murali4Shristika Yadav567BRUTE FORCE PHASE AND COMPROMISE DETECTION PHASE.8"""9import socket,sys10import time11import datetime12import threading1314socketDist={}15socks=[]16threads = []17connects = []18i=019username_host='sandhya'20password_host='1234'21list_logs=[]22run_event = threading.Event()23class Log:24    """25    Log created for storing log information about attacker26    """27    __slots__ = 'no_packets','conn_attempt_count','client_IP','auth_connection_successful','timestamp','total_packets'28    29    def __init__(self,conn_attempt_count,client_IP,timestamp,no_packets,total_packets):30            self.conn_attempt_count=conn_attempt_count31            self.client_IP=client_IP32            self.timestamp=timestamp33            self.no_packets=no_packets34            self.total_packets=total_packets3536    def __str__(self):37        return 'Log: '+str(self.client_IP)+ ' '+ str(self.conn_attempt_count)3839class CompromiseThread (threading.Thread):4041    def __init__(self, threadID, name, counter,connection):42        threading.Thread.__init__(self)43        self.threadID = threadID44        self.name = name45        self.counter = counter46        self.connection=connection47        self.data=None4849    def run(self):50        while True:51            self.data = receive_data(self.connection)52            if self.data!=0 and self.data.strip() !='':53                print(self.data)54                self.connection.sendall("ACK")55                print('Received Data')56            else:57                break58            time.sleep(5)5960    def fetch_Data(self):61        fdata = self.data62        self.data=None63        return fdata6465class BruteforceThread (threading.Thread):6667    def __init__(self, threadID, name,set):68        threading.Thread.__init__(self)69        self.threadID = threadID70        self.name = name71        self.set = set7273    def run(self):74        if self.set == True:75            bruteForce(self.threadID)76def scanThread(id):77    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)78    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)79    server_address = ('localhost', 10000 + id)80    print('starting up on %s port %s', server_address)81    sock.bind(server_address)82    sock.listen(1)83    # Wait for a connection84    print('waiting for a connection')85    connection, client_address = sock.accept()86    nack = connection.recv(16)87    if nack=='NACK':88        connection.close()89    sock.close()9091def genuineConnection(connection):92    data=''93    try:94        while data!='NACK':95            data=connection.recv(16)96            print('Received Data', data)97            if data!='NACK':98                connection.sendall("ACK")99            else:100                connects.remove(connection)101                connection.close()102    except:103        print('Connection closed.')104105106def bruteForce(id):107    """108    Brute force phase109    :param id: thread id.110    :return:111    """112    # Create a TCP socket113    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)114    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)115    socks.append(sock)116    # Bind the socket to the port117    server_address = ('localhost', 10000+id)118    print('starting up on %s port %s', server_address)119    sock.bind(server_address)120    sock.listen(1)121122    while True:123        # Wait for a connection124        print('waiting for a connection')125        connection, client_address = sock.accept()126        connects.append(connection)127        if len(connects)>1:128            print(connects[0].getsockname())129        flag_close=False130131        flag_present=False132        for i in range(len(list_logs)):133            if(list_logs[i].client_IP[0]==client_address[0] and list_logs[i].client_IP[1]==client_address[1]):134                flag_present=True135                if(list_logs[i].conn_attempt_count>=5):136                    list_logs[i].timestamp=time.time()137                    index=i138                    while (True):139                        connection.sendall("NACK")140                        nack = connection.recv(16)141                        if (nack == "NACK"):142                            #connection.close()143                            flag_close = True144                            break145                    break146                else:147                    list_logs[i].conn_attempt_count+=1148                    list_logs[i].timestamp=time.time()149                    break150151        if(flag_present==True and list_logs[index].conn_attempt_count>=5):152            break153154155        elif(flag_present==False):156            log=Log(1,client_address,time.time(),0,0)157            list_logs.append(log)158159        try:160                while True:161                    for i in range(len(list_logs)):162                        if(list_logs[i].client_IP==client_address):163                            index=i164                            break165166                    if(flag_close==True and list_logs[index].conn_attempt_count<5):167                        connection, client_address = sock.accept()168                        connects.append(connection)169                        print(connects[0].getsockname())170                        for i in range(len(list_logs)):171                            if(list_logs[i].client_IP==client_address):172                                index=i173                                break174                        list_logs[index].conn_attempt_count+=1175                        list_logs[index].timestamp=time.time()176177                        flag_close=False178179                    elif(flag_close==True and list_logs[index].conn_attempt_count>=5):180                        connection, client_address = sock.accept()181                        connection.sendall("NACK")182                        connection.close()183                        break184185                    if(flag_close==False):186                        #print('connection from', client_address)187                        index=0188                        for i in range(len(list_logs)):189                            if(list_logs[i].client_IP==client_address):190                                index=i191                                break192                        #print(list_logs[index].no_packets,list_logs[index].total_packets)193                        connection.sendall("Enter username")194                        list_logs[index].no_packets+=1195                        list_logs[index].total_packets+=1196                        username = connection.recv(16)197                        list_logs[index].no_packets+=1198                        list_logs[index].total_packets+=1199                        connection.sendall("Enter password")200                        list_logs[index].no_packets+=1201                        list_logs[index].total_packets+=1202                        password = connection.recv(16)203                        list_logs[index].no_packets+=1204                        list_logs[index].total_packets+=1205                        print("Username Received",username)206                        print("Password Received",password)207208                        if(username_host==username and password_host==password):209                            list_logs[index].auth_connection_successful=True210                            connection.sendall("SUCCESS")211                            list_logs[index].no_packets=0212                            if list_logs[index].conn_attempt_count>2:213                                compromise(client_address,connection,sock)214                            else:215                                genuineConnection(connection)216                            break217                            #successfull218                        else:219                            list_logs[index].auth_connection_successful=False220221                            print(list_logs[index].client_IP,list_logs[index].no_packets )222                            if(list_logs[index].no_packets>=12):223224                                list_logs[index].no_packets=0225226                                while (True):227                                    connection.sendall("NACK")228                                    nack = connection.recv(16)229                                    if (nack == "NACK"):230                                        #connection.close()231                                        flag_close = True232                                        break233                        if(flag_close==True):234                            connects.remove(connection)235                            connection.close()236237238        finally:239            # Clean up the connection240            if connection in connects:241                connects.remove(connection)242            connection.close()243244245def receive_data(connection):246    """247248    :param connection:249    :return:250    """251    data=0252    try:253        data=connection.recv(16)254    except:255        print('Connection closed from Client')256    return data257258259def compromise(client_address,connection,sock):260    """261    Compromise detection phase.262    """263    thread1 = CompromiseThread(1, "Thread-1", 1,connection)264    time_pkts_received=[]265    datasize_pkts_received=[]266    monitoring_start_time = datetime.datetime.now()267    connection_closed=False268    thread1.start()269    while datetime.datetime.now()<(monitoring_start_time + datetime.timedelta(minutes = 1)):270        data = thread1.fetch_Data()271        if data != None:272            if data != 0 and data !='':273                time_pkts_received.append(datetime.datetime.now())274                datasize_pkts_received.append(data)275                connection.sendall('ACK')276            else:277                thread1.join()278                # connection closed from client279                connection_end_time= datetime.datetime.now()280                connection_closed=True281                # Compromise phase detected, Instant logout, Continue dictionary282                if len(time_pkts_received)<1:283                    minutes,seconds=divmod((connection_end_time - monitoring_start_time).total_seconds(), 60)284                    no_of_pkts_per_time = len(time_pkts_received)/((minutes*60+seconds)*30)285                    log_received = None286                    for log in list_logs:287                        if log.client_IP[0] == client_address[0]:288                            log_received = log289                            break290                    if no_of_pkts_per_time<3 and log_received!=None and log_received.conn_attempt_count>2:291                        print("Compromise phase detected, Instant logout, Continue dictionary")292                    connects.remove(connection)293                    connection.close()294                # Compromise phase detected, Instant logout, Abort dictionary295                elif len(time_pkts_received)==1 and datasize_pkts_received[0] == 'CLOSE ALL':296                    log_received=None297                    for log in list_logs:298                        if log.client_IP[0] == client_address[0]:299                            log_received=log300                            break301                    if log_received!=None and log_received.conn_attempt_count>2:302                        log_received.auth_connection_successful = True303                        #connection.sendall("NACK")304                        #print('connection', connection.getsockname())305                        i=0306                        while len(connects)>1:307                            if connects[i]!=connection:308                                #print(connects[i].getsockname())309                                connects[i].sendall("NACK")310                                connects[i].close()311                                connects.pop(i)312                            else:313                                i+=1314315                        for i in range(len(threads)):316                            threads[i].set=False317318                        run_event.clear()319320                        print('Compromise phase detected, Instant logout, Abort dictionary')321                        #print(connects[0].getsockname())322                        #connects.remove(connection)323                        connection.close()324325                break326        else:327            time.sleep(.5)328329    if not connection_closed:330        # monitored the traffic for 2 minutes.331        connection_end_time = datetime.datetime.now()332        # Compromise phase detected, Maintain connection, Continue dictionary.333        if datasize_pkts_received[0] != 'CLOSE ALL':334            minutes, seconds = divmod((connection_end_time - monitoring_start_time).total_seconds(), 60)335            no_of_pkts_per_time = len(time_pkts_received) / ((minutes * 60 + seconds) * 30)336            if no_of_pkts_per_time < 3:337                print("Compromise phase detected, Maintain connection, Continue dictionary \n Closing connection with Attacker")338                connection.sendall("NACK")339                connects.remove(connection)340                connection.close()341        # Compromise phase detected, Maintain connection, Abort dictionary.342        elif datasize_pkts_received[0] == 'CLOSE ALL':343            print("Compromise phase detected, Maintain connection, Abort dictionary \n Closing connection with Attacker")344            i = 0345            while len(connects) > 1:346                if connects[i] != connection:347                    connects[i].sendall("NACK")348                    connects[i].close()349                    connects.pop(i)350                else:351                    i += 1352353            connection.close()354355def main():356    #  Thread list357    threadList = [1,2,3,4,5]358    # thread connections per attacker.359    for i in range(len(threadList)):360        t=BruteforceThread(threadList[i], "Thread"+str(threadList[i]), True)361        threads.append(t)362    for i in range(len(threads)):363        threads[i].start()364        time.sleep(.5)365366    try:367        while True:368            time.sleep(.1)369    except KeyboardInterrupt:370        run_event.clear()371        for i in range(len(threads)):372            threads[i].join()373        for i in range(len(connects)):374            connects[i].close()375        for i in range(len(socks)):376            socks[i].close()377        print("Threads successfully closed")378379if __name__ == '__main__':380    main()381382
...flask_managing.py
Source:flask_managing.py  
1from . import selenium_management2from ..log import dbMangements as logs3from flask import request4from flask import Flask5from sys import version6from rq import Queue7from worker import conn8from rq.job import Job9from flask import jsonify10q=Queue(connection=conn)11app=Flask(__name__)12app.config['JSON_AS_ASCII']=False13@app.route("/")14def index():15    return "uWSGI from python version: <br>" + version16@app.route('/naver', methods=['GET'])17def naver():18    #start = datetime.datetime.now()19    naverID = request.args.get('naverID')20    content_number = request.args.get('article')21    url="https://blog.naver.com/{0}/{1}".format(naverID,content_number)22    job= q.enqueue_call(func=selenium_management.request_code_parsing,args=(url,))23    job_id=job.get_id()24    return_result=get_result(job_id)25    if isinstance(return_result,str):26        #error status27        return jsonify(status="Error",message=return_result)28    else:29        title, source, result_list, list_hashtags = return_result30        return jsonify(title=title, source=source, details=result_list, tag=list_hashtags)31def get_result(job_key):32    while True:33        job = Job.fetch(job_key, connection=conn)34        value=job.return_value35        if value is None:36            import time37            time.sleep(1)38        else:break39    return value40@app.errorhandler(404)41def page_not_found(error):42	app.logger.error(error)43	logs.addToSystemLogs("404",str(error))44	return "<p>WRONG URL!!</p>"45@app.route('/logs')46def log():47    list_logs=logs.getLogs()48    list_logs=list(map(lambda x:"<p>"+'\t'.join(list(map(lambda y:str(y),x)))+"</p>", list_logs))49    return ''.join(list_logs)50@app.route('/systemlogs')51def systemlog():52    list_logs = logs.getSystemLogs()53    list_logs = list(map(lambda x: "<p>" + '\t'.join(list(map(lambda y: str(y), x))) + "</p>", list_logs))...main.py
Source:main.py  
1# -*- coding: utf-8 *-*2# imports3import os4import multiprocessing5import threading6import configparser7import sys8import traceback9import source.process as process10list_logs = []11logs_configs = []12debug_mode = True13def main():14    try:15        # configparser for get configurations16        cur_path = os.path.dirname(os.path.abspath(__file__))17        config = configparser.ConfigParser()18        config.read(cur_path + '/configs/config.ini')19        print(config)20        # diccionary with connections21        logs_configs = config['general']['names'].split(',')22        general_output_rute = config['general']['Output_rute']23        for log_ in logs_configs:24            list_logs.append(process.log_listener(25                log_, config[log_], general_output_rute))26            print(vars(list_logs[0]))27        print(list_logs)28        for run_logs in list_logs:29            process_ = None30            process_ = threading.Thread(target=run_logs.run)31            process_.start()32    except Exception as e:33        if debug_mode:34            print(traceback.format_exc())35        print(36            "\n\nSorry the configuration is bad please read the confiuration in the file README.md or if is a problem "37            "with the code please report franevarez@gmail.com\n")38if __name__ == '__main__':...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
