python类SOCKS5的实例源码

reachability-monitor.py 文件源码 项目:securedrop-reachability-monitor 作者: freedomofpress 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def check_instances(self, instances, timeout=30):
        """Visits each SD found in the directory and records its version
        string or the string 'unreachable', as well as relevant circuit
        information and descriptor information."""
        opener = build_opener(SocksiPyHandler(socks.SOCKS5, "127.0.0.1", 9050))

        for instance in instances:
            hs_url = instance.get("ths_address")

            try:
                response = opener.open("http://"+hs_url,
                                       timeout=timeout).read().decode()
                version_str = search("Powered by SecureDrop [0-9.]+",
                                     response).group(0)
                instance["version"] = version_str.split()[-1][:-1]
            except (socks.SOCKS5Error, socks.GeneralProxyError,
                    urllib.error.URLError):
                instance["version"] = "unreachable"
                try:
                    # The reason that we don't call the
                    # get_hidden_service_descriptor method on all URLs is that
                    # it's unreliable for services that are actually up.
                    # Basically, the method will never return or timeout. With
                    # services that cannot be reached, it usually quickly
                    # fails with the stem.DescriptorUnavailable exception. This
                    # seems to be the leading cause of unreachability.
                    hs_desc = self.controller.get_hidden_service_descriptor(hs_url)
                    instance["intro_pts"] = hs_desc.introduction_points_content.decode()
                except stem.DescriptorUnavailable:
                    instance["intro_pts"] = "descriptor unavailable"
                    print(instance)
                    continue
                pass

            intro_circs = []
            rend_circs = []

            for circuit in self.controller.get_circuits():
                if circuit.purpose == "HS_CLIENT_INTRO":
                    intro_circs.append(dict(path=circuit.path,
                                           reason=circuit.reason,
                                           remote_reason=circuit.remote_reason))
                if circuit.purpose == "HS_CLIENT_REND":
                    rend_circs.append(dict(path=circuit.path,
                                           state=circuit.hs_state,
                                           reason=circuit.reason,
                                           remote_reason=circuit.remote_reason))
                self.controller.close_circuit(circuit.id)

            instance["intro_circs"] = intro_circs
            instance["rend_circs"] = rend_circs

            if instance["version"] == "unreachable":
                print(instance)

        return instances
whois_connect.py 文件源码 项目:com_top_whois_service 作者: h-j-13 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def _connect(self):
        """??????whois??
        ???socks.py (ver 1.5.7)"""
        # whois???ip???ip
        global _server_ip, _proxy_socks
        host = _server_ip.get_server_ip(self.whois_srv)  # ?????
        host = host if host else self.whois_srv  # ??ip????????????
        self.tcpCliSock = socks.socksocket()  # ??socket??
        self.tcpCliSock.settimeout(TIMEOUT)  # ??????
        if Proxy_Flag:  # socks????
            proxy_info = _proxy_socks.get_proxy_socks(self.whois_srv)  # ??IP
            if proxy_info is not None:
                # ????
                if proxy_info['mode'] == 'SOCKS5':
                    self.tcpCliSock.set_proxy(proxy_type=socks.SOCKS5,  # socks??
                                              addr=proxy_info['ip'],  # socks???
                                              port=proxy_info['port'],  # ??
                                              username=proxy_info['username'],  # ???
                                              password=proxy_info['password'])  # ??

                elif proxy_info['mode'] == 'SOCKS4':
                    self.tcpCliSock.set_proxy(proxy_type=socks.SOCKS4,  # socks??
                                              addr=proxy_info['ip'],  # socks???
                                              port=proxy_info['port'])  # ??
        data_result = ""
        try:
            self.tcpCliSock.connect((host, 43))  # ??whois???
            self.tcpCliSock.send(self.request_data + '\r\n')  # ????
        except Exception as e:  # Exception??socks.py ??????
            if str(e).find("timed out") != -1 or \
                            str(e).find("TTL expired") != -1:  # ????
                self.tcpCliSock.close()
                return "ERROR -1"
            elif str(e).find("Temporary failure in name resolution") != -1 or \
                            str(e).find("cannot connect to identd on the client") != -1 or \
                            str(e).find("unreachable") != -1:
                self.tcpCliSock.close()
                return "ERROR -2"
            else:
                self.tcpCliSock.close()
                return "ERROR OTHER"
        # ????
        while True:
            try:
                data_rcv = self.tcpCliSock.recv(1024)  # ??????
            except:
                self.tcpCliSock.close()
                return "ERROR -3"
            if not len(data_rcv):
                self.tcpCliSock.close()
                return data_result  # ??????
            data_result = data_result + data_rcv  # ????????
whois_connect.py 文件源码 项目:Malicious_Domain_Whois 作者: h-j-13 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def _connect(self):
        """??????whois??
        ???socks.py (ver 1.5.7)"""
        # whois???ip???ip
        global _server_ip, _proxy_socks
        host = _server_ip.get_server_ip(self.whois_srv)  # ?????
        host = host if host else self.whois_srv  # ??ip????????????
        self.tcpCliSock = socks.socksocket()  # ??socket??
        self.tcpCliSock.settimeout(TIMEOUT)  # ??????
        if Proxy_Flag:  # socks????
            proxy_info = _proxy_socks.get_proxy_socks(self.whois_srv)  # ??IP
            if proxy_info is not None:
                # ????
                if proxy_info['mode'] == 'SOCKS5':
                    self.tcpCliSock.set_proxy(proxy_type=socks.SOCKS5,  # socks??
                                              addr=proxy_info['ip'],  # socks???
                                              port=proxy_info['port'],  # ??
                                              username=proxy_info['username'],  # ???
                                              password=proxy_info['password'])  # ??

                elif proxy_info['mode'] == 'SOCKS4':
                    self.tcpCliSock.set_proxy(proxy_type=socks.SOCKS4,  # socks??
                                              addr=proxy_info['ip'],  # socks???
                                              port=proxy_info['port'])  # ??
        data_result = ""
        try:
            self.tcpCliSock.connect((host, 43))  # ??whois???
            self.tcpCliSock.send(self.request_data + '\r\n')  # ????
        except Exception as e:  # Exception??socks.py ??????
            if str(e).find("timed out") != -1 or \
                            str(e).find("TTL expired") != -1:  # ????
                self.tcpCliSock.close()
                return "ERROR -1"
            elif str(e).find("Temporary failure in name resolution") != -1 or \
                            str(e).find("cannot connect to identd on the client") != -1 or \
                            str(e).find("unreachable") != -1:
                self.tcpCliSock.close()
                return "ERROR -2"
            else:
                self.tcpCliSock.close()
                return "ERROR OTHER"
        # ????
        while True:
            try:
                data_rcv = self.tcpCliSock.recv(1024)  # ??????
            except:
                self.tcpCliSock.close()
                return "ERROR -3"
            if not len(data_rcv):
                self.tcpCliSock.close()
                return data_result  # ??????
            data_result = data_result + data_rcv  # ????????
PhishingKitHunter.py 文件源码 项目:PhishingKitHunter 作者: t4d 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def get_page(ResRefererEx):
    global PK_status
    global htmlshash
    # Use a proxy if declared in config file
    try:
        # Use a HTTP proxy
        if proxy_type in 'http':
            http_proxy
            proxy_support = urllib.request.ProxyHandler({'http': http_proxy})
            opener = urllib.request.build_opener(proxy_support)
            urllib.request.install_opener(opener)
        # Use a SOCKS5 proxy
        elif proxy_type in 'socks':
            socks_proxy_server
            socks_proxy_port
            opener = urllib.request.build_opener(SocksiPyHandler(socks.SOCKS5, socks_proxy_server, int(socks_proxy_port), True))
            urllib.request.install_opener(opener)

    except NameError:
        pass

    try:
        request = urllib.request.Request(
        url=ResRefererEx,
        # Force user-agent
        headers={
                'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'
        }
        )
        response = urllib.request.urlopen(request, timeout=5)
        resp_code = response.getcode()
        htmldata = str(response.read().decode('utf-8'))

        if resp_code == 200:
            try:
                # If page contains tracking_file_request
                if RegRequest2.finditer(htmldata):
                    PK_status = 'UP'
                    # Create SHA256 hash of HTML page content
                    htmlshash = hashlib.sha256(htmldata.encode('utf-8')).hexdigest()
                else:
                    PK_status = 'Probably removed'
            except:
                err = sys.exc_info()
                print(err)
                pass
        else:
            PK_status = 'DOWN'

    except:
        #err = sys.exc_info()[1]
        err = sys.exc_info()[1]
        PK_status = ('can\'t connect ('+str(err)+')')
        pass

## Usage
engine.py 文件源码 项目:OWASP-Nettacker 作者: viraintel 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def login(user, passwd, target, port, timeout_sec, log_in_file, language, retries, time_sleep, thread_tmp_filename, socks_proxy):
    _HOST = messages(language, 53)
    _USERNAME = messages(language, 54)
    _PASSWORD = messages(language, 55)
    _PORT = messages(language, 56)
    _TYPE = messages(language, 57)
    _DESCRIPTION = messages(language, 58)
    exit = 0
    if socks_proxy is not None:
        socks_version = socks.SOCKS5 if socks_proxy.startswith('socks5://') else socks.SOCKS4
        socks_proxy = socks_proxy.rsplit('://')[1]
        socks.set_default_proxy(socks_version, str(socks_proxy.rsplit(':')[0]), int(socks_proxy.rsplit(':')[1]))
        socket.socket = socks.socksocket
        socket.getaddrinfo = getaddrinfo
    while 1:
        try:
            if timeout_sec is not None:
                my_ftp = FTP(timeout=timeout_sec)
            else:
                my_ftp = FTP()
            my_ftp.connect(target, port)
            exit = 0
            break
        except:
            exit += 1
            if exit is retries:
                warn(messages(language, 65).format(target, port, user, passwd))
                return 1
        time.sleep(time_sleep)
    flag = 1
    try:
        my_ftp.login(user, passwd)
        flag = 0
    except:
        pass
    if flag is 0:
        try:
            tmpl = []
            tmp = my_ftp.retrlines('LIST', tmpl.append)
            info(messages(language, 70).format(user, passwd, target, port))
            save = open(log_in_file, 'a')
            save.write(
                json.dumps({_HOST: target, _USERNAME: user, _PASSWORD: passwd, _PORT: port, _TYPE: 'ftp_brute',
                            _DESCRIPTION: messages(language, 66)}) + '\n')
            save.close()
        except:
            info(messages(language, 70).format(user, passwd, target, port) + ' ' + messages(language, 71))
            save = open(log_in_file, 'a')
            save.write(json.dumps({_HOST: target, _USERNAME: user, _PASSWORD: passwd, _PORT: port, _TYPE: 'FTP',
                                   _DESCRIPTION: messages(language, 67)}) + '\n')
            save.close()
        thread_write = open(thread_tmp_filename, 'w')
        thread_write.write('0')
        thread_write.close()
    else:
        pass
    return flag
engine.py 文件源码 项目:OWASP-Nettacker 作者: viraintel 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def login(user, passwd, target, port, timeout_sec, log_in_file, language, retries, time_sleep,
          thread_tmp_filename, socks_proxy):
    _HOST = messages(language, 53)
    _USERNAME = messages(language, 54)
    _PASSWORD = messages(language, 55)
    _PORT = messages(language, 56)
    _TYPE = messages(language, 57)
    _DESCRIPTION = messages(language, 58)
    exit = 0
    flag = 1
    if socks_proxy is not None:
        socks_version = socks.SOCKS5 if socks_proxy.startswith('socks5://') else socks.SOCKS4
        socks_proxy = socks_proxy.rsplit('://')[1]
        socks.set_default_proxy(socks_version, str(socks_proxy.rsplit(':')[0]), int(socks_proxy.rsplit(':')[1]))
        socket.socket = socks.socksocket
        socket.getaddrinfo = getaddrinfo
    while 1:
        try:
            paramiko.Transport((target, int(port)))
            paramiko_logger = logging.getLogger("paramiko.transport")
            paramiko_logger.disabled = True
            flag = 0
            exit = 0
            break
        except:
            exit += 1
            if exit is retries:
                warn(messages(language, 76).format(target, str(port), user, passwd))
                return 1
        time.sleep(time_sleep)
    if flag is 0:
        try:
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            if timeout_sec is not None:
                ssh.connect(hostname=target, username=user, password=passwd, port=int(port), timeout=timeout_sec)
            else:
                ssh.connect(hostname=target, username=user, password=passwd, port=int(port))
            info(messages(language, 70).format(user, passwd, target, port))
            save = open(log_in_file, 'a')
            save.write(
                json.dumps({_HOST: target, _USERNAME: user, _PASSWORD: passwd, _PORT: port, _TYPE: 'ssh_brute',
                            _DESCRIPTION: messages(language, 66)}) + '\n')
            save.close()
            thread_write = open(thread_tmp_filename, 'w')
            thread_write.write('0')
            thread_write.close()
        except:
            pass
    else:
        pass
    return flag
engine.py 文件源码 项目:OWASP-Nettacker 作者: viraintel 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def login(user, passwd, target, port, timeout_sec, log_in_file, language, retries, time_sleep, thread_tmp_filename,
          socks_proxy):
    _HOST = messages(language, 53)
    _USERNAME = messages(language, 54)
    _PASSWORD = messages(language, 55)
    _PORT = messages(language, 56)
    _TYPE = messages(language, 57)
    _DESCRIPTION = messages(language, 58)
    exit = 0
    if socks_proxy is not None:
        socks_version = socks.SOCKS5 if socks_proxy.startswith('socks5://') else socks.SOCKS4
        socks_proxy = socks_proxy.rsplit('://')[1]
        socks.set_default_proxy(socks_version, str(socks_proxy.rsplit(':')[0]), int(socks_proxy.rsplit(':')[1]))
        socket.socket = socks.socksocket
        socket.getaddrinfo = getaddrinfo
    while 1:
        try:
            if timeout_sec is not None:
                server = smtplib.SMTP(target, int(port), timeout=timeout_sec)
            else:
                server = smtplib.SMTP(target, int(port))
            server.starttls()
            exit = 0
            break
        except:
            exit += 1
            if exit is retries:
                warn(messages(language, 73).format(target, port, user, passwd))
                return 1
        time.sleep(time_sleep)
    flag = 1
    try:
        server.login(user, passwd)
        flag = 0
    except smtplib.SMTPException as err:
        pass
    if flag is 0:
        info(messages(language, 70).format(user, passwd, target, port))
        save = open(log_in_file, 'a')
        save.write(json.dumps({_HOST: target, _USERNAME: user, _PASSWORD: passwd, _PORT: port, _TYPE: 'smtp_brute',
                               _DESCRIPTION: messages(language, 66)}) + '\n')
        save.close()
        thread_write = open(thread_tmp_filename, 'w')
        thread_write.write('0')
        thread_write.close()
    else:
        pass
    try:
        server.quit()
    except:
        pass
    return flag
engine.py 文件源码 项目:OWASP-Nettacker 作者: viraintel 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def check(target, user_agent, timeout_sec, log_in_file, language, time_sleep, thread_tmp_filename, retries,
          http_method, socks_proxy):
    _HOST = messages(language, 53)
    _USERNAME = messages(language, 54)
    _PASSWORD = messages(language, 55)
    _PORT = messages(language, 56)
    _TYPE = messages(language, 57)
    _DESCRIPTION = messages(language, 58)
    status_codes = [200, 401, 403]
    directory_listing_msgs = ["<title>Index of /", "<a href=\"\\?C=N;O=D\">Name</a>", "Directory Listing for",
                              "Parent Directory</a>", "Last modified</a>", "<TITLE>Folder Listing.",
                              "- Browsing directory "]
    time.sleep(time_sleep)
    try:
        if socks_proxy is not None:
            socks_version = socks.SOCKS5 if socks_proxy.startswith('socks5://') else socks.SOCKS4
            socks_proxy = socks_proxy.rsplit('://')[1]
            socks.set_default_proxy(socks_version, str(socks_proxy.rsplit(':')[0]), int(socks_proxy.rsplit(':')[1]))
            socket.socket = socks.socksocket
            socket.getaddrinfo = getaddrinfo
        n = 0
        while 1:
            try:
                if http_method == "GET":
                    r = requests.get(target, timeout=timeout_sec, headers=user_agent, verify=True)
                elif http_method == "HEAD":
                    r = requests.head(target, timeout=timeout_sec, headers=user_agent, verify=True)
                content = r.content
                break
            except:
                n += 1
                if n is retries:
                    warn(messages(language, 106).format(target))
                    return 1
        if version() is 3:
            content = content.decode('utf8')
        if r.status_code in status_codes:
            info(messages(language, 38).format(target, r.status_code, r.reason))
            thread_write = open(thread_tmp_filename, 'w')
            thread_write.write('0')
            thread_write.close()
            save = open(log_in_file, 'a')
            save.write(json.dumps({_HOST: target_to_host(target), _USERNAME: '', _PASSWORD: '',
                                   _PORT: int(target.rsplit(':')[2].rsplit('/')[0]), _TYPE: 'dir_scan',
                                   _DESCRIPTION: messages(language, 38).format(target, r.status_code,
                                                                               r.reason)}) + '\n')
            save.close()
            if r.status_code is 200:
                for dlmsg in directory_listing_msgs:
                    if dlmsg in content:
                        info(messages(language, 104).format(target))
                        save = open(log_in_file, 'a')
                        save.write(json.dumps({_HOST: target_to_host(target), _USERNAME: '', _PASSWORD: '',
                                               _PORT: int(target.rsplit(':')[1].rsplit('/')[0]), _TYPE: 'dir_scan',
                                               _DESCRIPTION: messages(language, 104).format(target)}) + '\n')
                        save.close()
                        break
        return True
    except:
        return False


问题


面经


文章

微信
公众号

扫码关注公众号