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

URL として ʹhttps://user:pass@whateverʹ を渡しています。Python は、認証しようとしていることを理解せず、「https://domain:port...」を渡していると考えます。

urllib で基本認証を行うには、urllib.request.HTTPBasicAuthHandler を使用する必要があります。

申し訳ありませんが、リンクやサンプルコードを投稿していませんが、携帯電話でこれを入力しているため、面倒です。

于 2013-09-07T22:54:23.987 に答える