Windows下用Python命令行创建GitHub仓库遇Bad credentials错误怎么解决
解决GitHub API创建仓库时的"Bad credentials"错误
我在Windows系统上用Python写了个命令行工具,想通过GitHub API创建新仓库,替代Hub工具。但运行代码时总是弹出Bad credentials错误,代码和错误信息如下:
原代码
######################################### # AUTHOR: Dennis Lucius # DATE: 19/10/2022 # GITHUB: https://github.com/denstream-io ######################################### from argparse import ArgumentParser from subprocess import call from os import getenv # new-repo (username) (reponame) (mode) # todo: covert to exe add to path if not (PAT := getenv("PAT")): raise RuntimeError("Github Acess token no set") parser = ArgumentParser(description="Creates new Github repository") group = parser.add_mutually_exclusive_group() group.add_argument("-n", "--new", action="store_true") parser.add_argument("username", help="Github username") parser.add_argument("repository", help="Repository name") parser.add_argument("description", help="Repository description") parser.add_argument("mode", help="private true or false") args = parser.parse_args() call( f' curl \ -X POST \ -H "Accept: application/vnd.github+json" \ -H "Authorization: Bearer <{PAT}>" \ https://api.github.com/user/repos \ -d "{{"name":{args.repository},"description": {args.description},"homepage":"https://github.com","private":{args.mode.islower()},"is_template":true}}"', shell=True, ) print("Done Creating Repo") if args.new: cmds = ( "git init", f"git remote add origin git@gtihub.com:{args.username}/{args.repository}.git", "git add .", "git commit -m 'first commit'", "git push -u -f origin master", ) for cmd in cmds: call(cmd, shell=True)
错误信息
{ "message": "Bad credentials", "documentation_url": "https://docs.github.com/rest" }
解决方法
1. 修正GitHub PAT的授权格式
原代码里的Authorization头把PAT放在了<>里,这是错误格式,正确写法是Bearer 你的PAT,不需要尖括号。
2. 验证PAT的有效性与权限
- 确认GitHub账号上生成的PAT勾选了
repo权限(创建仓库必须) - 检查Windows系统环境变量
PAT是否正确设置了令牌值,可在命令行执行echo %PAT%验证
3. 修复curl请求的JSON格式错误
原代码的-d参数存在多处格式问题:
- 仓库名、描述未加引号,导致JSON结构失效
args.mode.islower()返回的是Python布尔值,GitHub API需要小写的true/false字符串- 双引号转义错误,导致JSON解析失败
4. 修正Git远程地址拼写错误
原代码里的git@gtihub.com是拼写错误,正确地址为git@github.com
修正后的完整代码
######################################### # AUTHOR: Dennis Lucius # DATE: 19/10/2022 # GITHUB: https://github.com/denstream-io ######################################### from argparse import ArgumentParser from subprocess import call from os import getenv # new-repo (username) (reponame) (mode) # todo: convert to exe add to path if not (PAT := getenv("PAT")): raise RuntimeError("Github Access token not set") parser = ArgumentParser(description="Creates new Github repository") group = parser.add_mutually_exclusive_group() group.add_argument("-n", "--new", action="store_true") parser.add_argument("username", help="Github username") parser.add_argument("repository", help="Repository name") parser.add_argument("description", help="Repository description") parser.add_argument("mode", help="private true or false") args = parser.parse_args() # 处理private参数,转为符合API要求的小写布尔字符串 is_private = args.mode.strip().lower() == "true" # 构造正确的curl命令,修复JSON格式和授权头 call( f'''curl \ -X POST \ -H "Accept: application/vnd.github+json" \ -H "Authorization: Bearer {PAT}" \ https://api.github.com/user/repos \ -d "{{\\"name\\":\\"{args.repository}\\",\\"description\\": \\"{args.description}\\",\\"homepage\\":\\"https://github.com\\",\\"private\\":{str(is_private).lower()},\\"is_template\\":true}}"''', shell=True, ) print("Done Creating Repo") if args.new: cmds = ( "git init", f"git remote add origin git@github.com:{args.username}/{args.repository}.git", "git add .", "git commit -m 'first commit'", "git push -u -f origin master", ) for cmd in cmds: call(cmd, shell=True)
额外建议
- 尽量避免用
subprocess.call执行curl,直接用Python的requests库调用API会更可靠,也更容易调试 - 生成PAT时遵循最小权限原则,只勾选必要权限
- 添加错误处理逻辑,检查命令执行结果,避免仓库创建失败后继续执行后续Git操作
内容的提问来源于stack exchange,提问作者densteam-io
相关产品推荐
相关产品推荐

