【发布时间】:2023-01-31 19:48:56
【问题描述】:
我正在构建一个启动并连接到 EC2 实例的脚本。在实例的所有设置之后,我必须将我的私人仓库复制到它,然后运行它。该代码适用于公共回购。 此外,如果我手动启动一个实例,连接到它并逐行运行,它也可以正常工作。我正在使用 python、boto3 和 paramiko。
这是我到目前为止所拥有的:
print("Creating ssh key pair...")
stdin, stdout, stderr = client.exec_command('ssh-keygen -t rsa -b 4096 -C "myemail@gmail.com" -f ~/.ssh/id_rsa -N ""')
output = stdout.read().decode()
print(output)
print("Done")
# add ssh key to ssh-agent
print("Adding ssh key to ssh agent")
stdin, stdout, stderr = client.exec_command('eval "$(ssh-agent -s)" ; ssh-add ~/.ssh/id_rsa')
output = stdout.read().decode()
print(output)
stdin, stdout, stderr = client.exec_command('ssh-keyscan github.com >> ~/.ssh/known_hosts')
output = stdout.read().decode()
print(output)
# add ssh key to github account
print("Adding ssh key to github account...")
stdin, stdout, stderr = client.exec_command('curl -u "myusername:mytoken" -H "Content-Type: application/json" --data "{\"title\":\"EC2_Instance_Key\",\"key\":\"$(cat ~/.ssh/id_rsa.pub)\"}" https://api.github.com/user/keys -X POST')
output = stdout.read().decode()
print(output)
print("Done")
# clone the repository
print("Cloning the repository to the instance...")
stdin, stdout, stderr = client.exec_command('git clone -o "StrictHostKeyChecking=no" git@github.com:myOrganization/ec2_test.git /home/ec2-user/project')
output = stdout.read().decode()
print(output)
print("Done")
我收到此错误:
% Total % Received % Xferd 平均速度 时间 时间 时间 当前的 Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0curl: (6) 无法解析主机:AAAAB3NzaC1yc2EAAAADAQABAAACAQDH50Rl curl: (3) 不匹配的关闭 URL 位置 18 中的大括号:myemail@gmail.com}
【问题讨论】:
-
经过一些调试后,我认为问题出在我将 ssh 密钥添加到我的 github 帐户的地方。但我仍然无法弄清楚为什么它在 ssh 连接上手动工作正常,但在我运行 scrip 时却不行。
-
从你的问题中不清楚问题是什么。私人回购的脚本是否失败?有没有错误信息?
-
如果我在与 EC2 实例的 ssh 连接中手动运行命令,它工作正常。但是对于凭据,它并没有将公钥添加到我的 github 帐户中。它不输出任何错误。
-
边注:与其使用 SSH 配置实例,不如考虑通过用户数据传递脚本。它会在第一次启动时自动执行。见:Run commands on your Linux instance at launch - Amazon Elastic Compute Cloud
标签: python amazon-web-services amazon-ec2 boto3 paramiko