如果连接时间过长,如何停止并说连接超时?

时间:2015-07-11 12:51:34

标签: python

如果连接时间太长,我怎么能停止它,它会卡在

**检查主持人:http://221.22.145.11 **

工作主持人:http://50.22.1.238:8090

关闭的主持人:http://221.22.145.11

            # coding: utf-8
    # JexBoss v1.0. @autor: João Filho Matos Figueiredo (joaomatosf@gmail.com)
    # Updates: https://github.com/joaomatosf/jexboss
    # Free for distribution and modification, but the authorship should be preserved.


    import httplib, sys, urllib, os, time
    from urllib import urlencode

    RED = '\x1b[91m'
    RED1 = '\033[31m'
    BLUE = '\033[94m'
    GREEN = '\033[32m'
    BOLD = '\033[1m'
    NORMAL = '\033[0m'
    ENDC = '\033[0m'

    def getHost(url):
        tokens = url.split("://")
        if len(tokens) == 2: #foi fornecido protocolo
            return tokens[1].split(":")[0]
        else:
            return tokens.split(":")[0]

    def getProtocol(url):
        tokens = url.split("://")
        if tokens[0] == "https":
            return "https"
        else:
            return "http"

    def getPort(url):
        token = url[6:].split(":")
        if len(token) == 2:
            return token[1]
        elif getProtocol(url) == "https":
            return 443
        else:
            return 80

    def getConnection(url):
        if getProtocol(url) == "https":
            return httplib.HTTPSConnection(getHost(url), getPort(url))
        else:
            return httplib.HTTPConnection(getHost(url), getPort(url))


    def getSuccessfully(url, path):
            result = 404
            time.sleep(5)
            conn = getConnection(url)
            conn.request("GET", path)
            result = conn.getresponse().status
            if result == 404:
                conn.close()
                time.sleep(7)
                conn = getConnection(url)
                conn.request("GET", path)
                result = conn.getresponse().status
                conn.close()
            return result

    def checkVul(url):

        print ( GREEN +" ** Checking Host: %s **\n" %url )

        path = { "jmx-console"       : "/jmx-console/HtmlAdaptor?action=inspectMBean&name=jboss.system:type=ServerInfo",
                 "web-console"       : "/web-console/ServerInfo.jsp",
                 "JMXInvokerServlet" : "/invoker/JMXInvokerServlet"}

        for i in path.keys():
            try:
                print GREEN + " * Checking %s: \t" %i + ENDC,
                conn = getConnection(url)
                conn.request("HEAD", path[i])
                path[i] = conn.getresponse().status
                if path[i] == 200 or path[i] == 500:
                    print RED + "[ VULNERABLE ]" + ENDC
                else: print GREEN + "[ OK ]"
                conn.close()
            except:
                print RED + "\n * An error ocurred while contaction the host %s\n" %url + ENDC
                path[i] = 505

        return path

    def clear():
        if os.name == 'posix':
            os.system('clear')
        elif os.name == ('ce', 'nt', 'dos'):
            os.system('cls')

    def checkArgs(args):
        if len(args) < 2 or args[1].count('.') < 1:
            return 1,"You must provide the host name or IP address you want to test."
        elif len(args[1].split('://')) == 1:
            return 2, 'Changing address "%s" to "http://%s"' %(args[1], args[1])
        elif args[1].count('http') == 1 and args[1].count('.') > 1:
            return 0, ""
        else:
            return 1, 'Parâmetro inválido'

    def banner():
        clear()
        print (RED1+"\n * --- JexBoss: Jboss verify and EXploitation Tool  --- *\n"
                  " |                                                      |\n"
                  " | @author:  João Filho Matos Figueiredo                |\n"
                  " | @contact: joaomatosf@gmail.com                       |\n"
                  " |                                                      |\n"
                  " | @update: https://github.com/joaomatosf/jexboss       |\n"
                  " #______________________________________________________#\n\n" )

    banner()
    # check python version
    if sys.version_info[0] == 3:
        print (RED + "\n * Not compatible with version 3 of python.\n"
                      "   Please run it with version 2.7 or lower.\n\n"
                +BLUE+" * Example:\n"
                      "   python2.7 " + sys.argv[0]+ " https://example.com\n\n"+ENDC )
        sys.exit(1)

    # check Args
    status, message = checkArgs(sys.argv)
    if status == 0:
        url = sys.argv[1]
    elif status == 1:
        print RED + "\n * Error: %s" %message
        print BLUE + "\n Example:\n python %s https://site.com.br\n" %sys.argv[0] + ENDC
        sys.exit(status)
    elif status == 2:
        url = ''.join(['http://',sys.argv[1]])

    # check vulnerabilities
    mapResult = checkVul(url)

    # performs exploitation
    for i in ["jmx-console", "web-console", "JMXInvokerServlet"]:
        if mapResult[i] == 200 or mapResult[i] == 500:
            print BLUE + ("\n\n * Do you want to try to run an automated exploitation via \""+BOLD+i+NORMAL+"\" ?\n"
                          "   This operation will provide a simple command shell to execute commands on the server..\n"
                     +RED+"   Continue only if you have permission!" +ENDC)
            if raw_input("   yes/NO ? ").lower() == "yes":
                autoExploit(url, i)

    # resume results
    if mapResult.values().count(200) > 0:
        banner()
        print RED+ " Results: potentially compromised server!" +ENDC
        print (GREEN+" * - - - - - - -  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*\n\n"
                  " Recommendations: \n"
                  " - If possible, discard this server!\n\n"
                  " * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*\n" )
    elif mapResult.values().count(505) == 0:
        print ( GREEN+ "\n\n * Results: \n"
                "   The server is not vulnerable to bugs tested ... :D\n\n" + ENDC)

    # infos 
    print (ENDC+" * Info: review, suggestions, updates, etc: \n"
                 "   https://github.com/joaomatosf/jexboss\n"
                 "   joaomatosf@gmail.com\n")

    print ENDC

完整的代码是 https://raw.githubusercontent.com/joaomatosf/jexboss/master/jexboss.py

1 个答案:

答案 0 :(得分:1)

以这种方式使用REQUEST_TIMEOUT status code(取自Python文档):

>>> res = conn.getresponse()
>>> print res.status, res.reason
408 REQUEST_TIMEOUT

就像您在代码中检查响应状态代码一样:

path[i] = conn.getresponse().status
     if path[i] == 408:
         print 'Connection TimeOut'
     else: 'Connected'

编辑:通过以下方式在timeout功能中设置所需的getConnection(url)

def getConnection(url):
    if getProtocol(url) == "https":
        return httplib.HTTPSConnection(getHost(url), getPort(url),timeout=5)
    else:
        return httplib.HTTPConnection(getHost(url), getPort(url),timeout=5)

在此示例中,如果无法建立连接,该函数将尝试在5秒内连接到您的urltimeout