简体   繁体   中英

Check GitHub credentials validity

I am trying to verify GitHub credentials with Python.

I have tried this:

import urllib2, base64

username = "test@example.com"
password = "password"

request = urllib2.Request("https://github.com/")
base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
request.add_header("Authorization", "Basic %s" % base64string)   
result = urllib2.urlopen(request)

if result.code == 200:
    print "Success"
else:
    print "Error"

But it always returns Success , even with wrong password. What am I doing wrong?

Change the line

request = urllib2.Request("https://github.com/")

to

request = urllib2.Request("https://api.github.com/")

Try change your credentials. It is working for me.

Tested on

~/ $ python2 --version
Python 2.7.6
~/ $ uname -a
Linux wlysenko-Aspire 3.13.0-37-generic #64-Ubuntu SMP Mon Sep 22 21:28:38 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux

I should've been using https://api.github.com/user instead of https://github.com/ .

Nevertheless, I will use requests 3rd party library, which makes this code concise:

import requests
print requests.get(
    'https://api.github.com/user',
    auth=('username', 'password')
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM