繁体   English   中英

在 python 中验证 Github 私有仓库

[英]Autheticate Github private repo in python

我想验证给定的 repo URL、userid 和 password 组合是否有效。 我正在为此使用请求。 下面是我的python代码:

requests.get('https://github.com/geetikatalreja/WebApp_DotNet.git', auth = ('valid_username', 'Valid_password'))

或者

requests.get('https://github.com/geetikatalreja/WebApp_DotNet.git', auth=HTTPBasicAuth('valid_username', 'Valid_password'))

这两个语句都返回错误代码 401。错误代码 401 在需要身份验证但已失败或尚未提供时发生,但我可以使用来自 Github UI 的相同凭据和 URL 登录。

请协助。

如果您使用 GitHub API,但无法使用具有基本身份验证的 Web UI,则此类身份验证有效。

通常,Web UI 使用登录表单,该表单在您登录时发送 POST 请求。之后,使用会话 cookie 以保持登录状态(对于会话)。 如果在会话过期后登录仍然存在,则网站可以使用持续时间更长的 cookie。 我认为 GitHub 使用了这个概念。

我建议您将 API 用于自动化流程,因为您可以更轻松地解析响应。

另外,我强烈建议不要使用真实密码进行基本身份验证。 我会改用 PAT。

如果您想向 API 发送经过身份验证的请求,您可以执行

requests.get('https://api.github.com/repos/geetikatalreja/WebApp_DotNet', auth = ('valid_username', 'Valid_password'))

除了密码,您还可以使用您帐户的 PAT(这样更安全)。 你可以在那里创建一个 PAT。

GitHub的API文档可以发现这里和访问存储库的文档存在

您可以传入application/vnd.github.VERSION.diff媒体类型来获取差异。 这样就可以了

requests.get('https://api.github.com/geetikatalreja/WebApp_DotNet.git/:owner/:repo/pulls/:number', auth = ('valid_username', 'Valid_password'))

格式应该是这样的

requests.get('https://api.github.com/repos/:owner/:repo/pulls/:number', auth = ('valid_username', 'Valid_password'), headers=headers)

在哪里

headers = {
    'Authorization': 'token mygithubtoken',
    'Accept': 'application/vnd.github.VERSION.diff',
}

我们无法使用 OAuth 令牌访问该网站。 但是,差异可通过 API 获得:

https://developer.github.com/v3/pulls/#get-a-single-pull-request

请改用基于令牌的身份验证。 这是从github获取个人令牌的链接

https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line

获得令牌后,您可以-

  1. 从命令行登录
    $ git clone https://github.com/geetikatalreja/WebApp_DotNet.git
    Username: your_username
    Password: your_token
  1. 使用代码登录(Python urllib2 模块)
    url = "https://api.github.com/geetikatalreja/WebApp_DotNet.git/:owner/:repo/pulls/:number"
    token = "your_token"

    request = Request(url)
    request.add_header('Authorization', 'token %s' % token)
    response = urlopen(request) 
  1. 使用python请求模块登录
    import requests
    url = "https://github.com/geetikatalreja"
    response = requests.get(url, headers={'Authorization': 'your_token'})

但是出于某种原因,如果您必须使用用户名/密码登录,则可以使用以下代码

免责声明:代码未经测试,从这里复制。 此代码不使用 API 而是解析网页并进行登录

    s = requests.Session()
    r = s.get('https://www.github.com/login')
    tree = html.fromstring(r.content)
    data = {i.get('name'):i.get('value') for i in tree.cssselect('input')}
    data['login'] = username
    data['password'] = password
    r = s.post('https://github.com/session', data=data)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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