0

我不是 python 大师,我只是在编写代码来检查我的 api 身份验证和 URL 访问状态。我只想确保用户可以访问我的 api 和域 url。出于上述原因,我正在编写一个可以检查的 python 脚本,并且 cron 可以向我发送警报。

这是我的代码:

def check(argv):
    # I'm going to use argpase.It makes
    # command-line args a breeze.
    parser = argparse.ArgumentParser()
    parser.add_argument('-H', '--hostname', dest='hostname', required=True)
    parser.add_argument('-a', '--auth_id', dest='authenticationid')
    parser.add_argument('-t', '--auth_token', dest='authenticationtoken')
    parser.add_argument('-r', '--dest_url', dest='dest_url',help="""Path to report relative to root, like /v1/ OR /""", required=True)
    parser.add_argument("-q", "--quiet", action="store_false", dest="verbose", default=True,
        help="don't print status messages to stdout")
    args = vars(parser.parse_args())
    if args['authenticationid'] and args['authenticationtoken'] and not len(sys.argv) == 7:

        authurl = urllib.request.Request('https://{%s}:{%s}@%s%s/%s/' %(args['authenticationid'],args['authenticationtoken'],args['hostname'], args['dest_url'],args['authenticationid']))
        return (getAuthResponseCode(authurl))
    else:
        url = urllib.request.Request("https://%s%s" %(args['hostname'], args['dest_url']))
        return(getResponseCode(url))

def getResponseCode(url):
    try: 
        conn = urllib.request.urlopen(url,timeout=10)
        code = conn.getcode()
        return (status['OK'], code)
    except timeout:
        return (status['WARNING'], logging.error('socket timed out - URL %s', url))
    except urllib.error.URLError as e:
        return (status['CRITICAL'], e.reason)
    else:
        return (status['UNKNOWN'])

def getAuthResponseCode(authurl):
    try:
        authconn = urllib.request.urlopen(authurl, timeout=10)
        authcode = authconn.getcode()
        return (status['OK'], authcode)
    except timeout:
        return (status['WARNING'], logging.error('socket timed out - URL %s'))
    except urllib.error.URLError as err:
        return (status['CRITICAL'], err.reason)
    else:
        return (status['UNKNOWN'])

错误信息:

G:\Python>python check_http.py -H api.mydomain.com -r /API/Function/ -a 'MAMZMZZGVLMG
FMNTHIYTREETBESSS' -t 'DafniisfnsifnsifsbANBBDSDNBISDExODZlODAwMmZm'
Traceback (most recent call last):
  File "C:\Python33\lib\http\client.py", line 770, in _set_hostport
    port = int(host[i+1:])
ValueError: invalid literal for int() with base 10: "{'DafniisfnsifnsifsbANBBDSDNBISDExODZlODAw
MmZm'}@api.mydomain.com"

在处理上述异常的过程中,又出现了一个异常:

Traceback (most recent call last):
  File "check_http.py", line 76, in <module>
    print (check(sys.argv[1:]))
  File "check_http.py", line 41, in check
    return (getAuthResponseCode(authurl))
  File "check_http.py", line 61, in getAuthResponseCode
    authconn = urllib.request.urlopen(authurl, timeout=10)
  File "C:\Python33\lib\urllib\request.py", line 156, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Python33\lib\urllib\request.py", line 469, in open
    response = self._open(req, data)
  File "C:\Python33\lib\urllib\request.py", line 487, in _open
    '_open', req)
  File "C:\Python33\lib\urllib\request.py", line 447, in _call_chain
    result = func(*args)
  File "C:\Python33\lib\urllib\request.py", line 1283, in https_open
    context=self._context, check_hostname=self._check_hostname)
  File "C:\Python33\lib\urllib\request.py", line 1219, in do_open
    h = http_class(host, timeout=req.timeout, **http_conn_args)
  File "C:\Python33\lib\http\client.py", line 1172, in __init__
    source_address)
  File "C:\Python33\lib\http\client.py", line 749, in __init__
    self._set_hostport(host, port)
  File "C:\Python33\lib\http\client.py", line 775, in _set_hostport
    raise InvalidURL("nonnumeric port: '%s'" % host[i+1:])
http.client.InvalidURL: nonnumeric port: '{'DafniisfnsifnsifsbANBBDSDNBISDExODZlODAw
MmZm'}@api.mydomain.com'

我知道这不是写我的代码论坛,但我很无助,正在寻求帮助。如果有人能告诉我到底哪里出错了,我可以修复它。

我正在使用python3。

4

1 回答 1

1

您将 ʹhttps://user:pass@whateverʹ 作为 url 传递。Python 不理解您正在尝试进行身份验证,并认为您正在传递 ʹhttps://domain:port...ʹ

要使用 urllib 进行基本身份验证,您需要使用 urllib.request.HTTPBasicAuthHandler

抱歉,我没有发布链接和/或示例代码,但我在手机上输入了这个,这让我很痛苦。

于 2013-09-07T22:54:23.987 回答