使用Python+Boto3+Paramiko克隆私有GitHub仓库到EC2实例遇错求助
问题分析与修复方案
你的curl错误根源是公钥内容包含空格和特殊字符,直接嵌入shell命令的JSON参数时,被shell错误解析成了多个curl参数,导致curl把公钥的一部分当成了要访问的主机地址,同时JSON结构也被破坏(出现括号不匹配)。此外git clone的参数也有误,-o用来设置远程仓库名称,而非ssh的StrictHostKeyChecking选项。
具体修复步骤
1. 修复公钥上传的curl命令
先把公钥内容读取到shell变量,再用变量构造合法的JSON,避免shell解析时拆分参数:
替换原来的curl执行代码为:
# 读取公钥内容到shell变量,再构造JSON上传 cmd = ''' PUB_KEY=$(cat ~/.ssh/id_rsa.pub) curl -u "myusername:mytoken" \ -H "Content-Type: application/json" \ --data "{\"title\":\"EC2_Instance_Key\",\"key\":\"$PUB_KEY\"}" \ https://api.github.com/user/keys -X POST ''' stdin, stdout, stderr = client.exec_command(cmd) output = stdout.read().decode() # 打印 stderr 内容排查问题 print("Stderr:", stderr.read().decode()) print(output) print("Done")
如果实例上已安装jq(未安装可先执行yum install -y jq),可以用更稳妥的方式生成合法JSON,避免引号转义问题:
cmd = ''' PUB_KEY=$(cat ~/.ssh/id_rsa.pub) JSON_DATA=$(jq -n --arg title "EC2_Instance_Key" --arg key "$PUB_KEY" '{title: $title, key: $key}') curl -u "myusername:mytoken" \ -H "Content-Type: application/json" \ --data "$JSON_DATA" \ https://api.github.com/user/keys -X POST ''' stdin, stdout, stderr = client.exec_command(cmd) output = stdout.read().decode() print("Stderr:", stderr.read().decode()) print(output) print("Done")
2. 修复git clone的参数错误
-o是Git的远程仓库名称参数,StrictHostKeyChecking是ssh的配置项,需要通过GIT_SSH_COMMAND传递:
替换原来的git clone代码为:
print("Cloning the repository to the instance...") cmd = 'GIT_SSH_COMMAND="ssh -o StrictHostKeyChecking=no" git clone git@github.com:myOrganization/ec2_test.git /home/ec2-user/project' stdin, stdout, stderr = client.exec_command(cmd) output = stdout.read().decode() print("Stderr:", stderr.read().decode()) print(output) print("Done")
额外优化建议
- 执行每个命令后都打印
stderr内容,很多错误只会输出到标准错误流,方便排查问题。 - 生成ssh密钥前,先确保
~/.ssh目录存在:添加client.exec_command('mkdir -p ~/.ssh')。 - 上传GitHub密钥前,可先检查是否存在相同密钥,避免重复上传报错。
内容的提问来源于stack exchange,提问作者Higor Nunes
相关产品推荐
相关产品推荐

