简体   繁体   English

尝试从bash脚本将ssh键推入github时出错

[英]Error When trying to push ssh keys into github from bash script

I am working on a script that creates ssh keys and puts them into github using bash. 我正在研究一个脚本,该脚本创建ssh密钥,并使用bash将其放入github。 I am running into this error when running this function.. I want a way to generate ssh keys and put them into github from terminal within my script. 我在运行此函数时遇到此错误。我想要一种生成ssh密钥并将其从脚本中的终端放入github的方法。

sudo ssh-keygen -t rsa
KEY=$(sudo cat ~/.ssh/id_rsa.pub)
echo "Here is your KEY var: ${KEY}"
read -p "GitHub Username: " USERNAME
read -p "Please enter a title for you ssh key: " TITLE
curl --user "\"${USERNAME}"\" -X POST --data '{ "\"title"\": "\"$TITLE"\", "\"key"\": "\"$KEY"\" }' https://api.github.com/user/keys

Error: { "message": "Bad credentials", "documentation_url": " https://developer.github.com/v3 " } 错误:{“消息”:“凭证不正确”,“ documentation_url”:“ https://developer.github.com/v3 ”}

You are putting too many quotes in the command. 您在命令中添加了过多的引号。 The correct code (to a first approximation) would be 正确的代码(大致近似)为

curl --user "${USERNAME}" -X POST \
     --data "{ \"title\": \"$TITLE\", \"key\": \"$KEY\" }" \
     https://api.github.com/user/keys

However this is prone to failure if either TITLE or KEY contains a character that needs to be escaped to include in JSON. 但是,如果TITLEKEY包含需要转义以包含在JSON中的字符,则很容易失败。 The right way to do this is to generate the JSON with a tool like jq , which takes care of any necessary escaping. 正确的方法是使用jq类的工具生成JSON,该工具会处理所有必要的转义操作。

curl --user "${USERNAME}" -X POST \
     --data "$(jq -n --arg t "$TITLE" --arg k "$KEY" \
                  '{title: $t, key: $k}')" \
     https://api.github.com/user/keys

or 要么

jq -n --arg t "$TITLE" --arg k "$KEY" '{title: $t, key: $k}' |
  curl --user "$USERNAME" -X POST --data @- https://api.github.com/user/keys

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

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