Docker容器中无需SSH密钥执行git pull的方法咨询
我现在要管理Docker容器里的多个Git仓库,目标是每次启动容器时自动更新这些仓库。我在容器里跑了一个Python脚本,遍历所有仓库文件夹执行git pull,但报错:fatal: could not read Username for 'https://github.com': No such device or address。搜索到的方案都是在容器里配置SSH密钥,但这个方法不够易用——其他使用容器工具的人不一定都用SSH密钥。想问问有没有不用SSH密钥就能执行git pull的方法?
以下是我的Dockerfile和downloader.py代码:
Dockerfile
# Dockerfile to run Git Truck https://github.com/git-truck/git-truck FROM node:latest LABEL MANTAINER="jcarrascoa7" # Set the working directory in the image WORKDIR /app # Copy all files from the directory where the Dockerfile is located to /app (this Dockerfile must be in the same # directory as the GitHub repositories that will be analyzed) COPY . . # Install dependencies RUN apt-get update RUN apt-get upgrade RUN apt-get -y install xdg-utils --fix-missing RUN apt-get -y install git RUN npm install git-truck # Update repositories and run Git Truck CMD python3 downloader.py;npx git-truck@latest
downloader.py
import os __author__ = "Jose Antonio Castro" __github__ = "Baelfire18" main = os.getcwd() groups = [f"group1", f"group2", f"group3", f"group4"] repositories = ["repo1", "repo2", "repo3"] for group in groups: for repo in repositories: name = f"{group}-{repo}" try: if not os.path.exists(name): print(f"Git cloning {name}") os.system(f"git clone https://github.com/iic2154-uc-cl/{name}.git") else: print(f"Git pulling {name}") os.chdir(name) os.system("git stash") os.system("git pull --ff-only") except Exception as error: print(f'Error con {name}.\n{error}\nprint("F")') finally: os.chdir(main) print("\n")
无需SSH密钥的解决方案
1. 使用Git凭证助手(推荐)
在容器中配置Git的凭证存储助手,让Git自动保存凭证,后续拉取无需重复输入。
首先在Dockerfile中添加全局配置:
RUN git config --global credential.helper 'store --file ~/.git-credentials'
然后修改downloader.py,启动时从环境变量读取GitHub用户名和个人访问令牌(PAT),写入凭证文件:
# 在脚本开头添加 github_user = os.getenv('GITHUB_USER') github_token = os.getenv('GITHUB_TOKEN') if github_user and github_token: with open('/root/.git-credentials', 'w') as f: f.write(f'https://{github_user}:{github_token}@github.com\n') os.system('git config --global credential.helper store')
启动容器时传递环境变量即可:
docker run -e GITHUB_USER=你的用户名 -e GITHUB_TOKEN=你的PAT 你的镜像名
注:推荐用GitHub个人访问令牌(PAT)代替密码,权限更可控,安全性更高
2. 临时传递凭证执行拉取
如果不想保存凭证,可在git pull时直接通过URL传递凭证,同时关闭Git的交互提示:
修改downloader.py中的拉取逻辑:
# 先从环境变量拿凭证 github_user = os.getenv('GITHUB_USER') github_token = os.getenv('GITHUB_TOKEN') # 拉取时指定带凭证的远程地址 os.system(f"git pull https://{github_user}:{github_token}@github.com/iic2154-uc-cl/{name}.git --ff-only")
这种方法每次拉取都传递一次凭证,适合临时场景,不会留下凭证文件。
3. URL嵌入凭证(仅测试用)
直接把凭证嵌入到克隆/远程仓库的URL中,Git会自动用这个凭证验证:
修改克隆命令:
os.system(f"git clone https://{github_user}:{github_token}@github.com/iic2154-uc-cl/{name}.git")
已克隆的仓库可以修改远程地址:
os.system(f"git remote set-url origin https://{github_user}:{github_token}@github.com/iic2154-uc-cl/{name}.git")
注意:这种方式凭证会暴露在容器日志、进程列表里,绝对不要在生产环境使用
4. 组织级部署令牌(团队场景)
如果仓库属于组织,可创建GitHub部署令牌或GitHub App生成的令牌,将令牌作为环境变量传递给容器。这类令牌权限更精准,适合团队共享容器的场景,本质和PAT用法一致。
内容的提问来源于stack exchange,提问作者José Carrasco

