在运行脚本之前使用 Github.com 检查 ssh

Ale*_*lls 7 git ssh github

我有这个:

ssh -T git@github.com || {
  echo "Could not ssh to/with Github, check your auth";
  exit 1;
}
Run Code Online (Sandbox Code Playgroud)

我得到:

Hi ORESoftware! You've successfully authenticated, but GitHub does not provide shell access.
Could not ssh to/with Github, check your auth
Run Code Online (Sandbox Code Playgroud)

由于退出代码不为零,我是否真的需要解析输出以查看是否可以建立身份验证?

Ari*_*ler 7

运行时我期望只有 2 个返回值ssh -T git@github.com

  1. 1: 用户已通过身份验证,但无法使用 GitHub 打开 shell
  2. 255: 用户未经过身份验证

由于 @VonC 描述的原因,您永远不会得到 0 返回码。这意味着您不能使用 fun bash 简写来检查返回代码,例如短路逻辑检查 - 您必须明确记录和检查$?.


这是我用来检查我是否获得 GitHub 授权的 shell 脚本:

function github-authenticated() {
  # Attempt to ssh to GitHub
  ssh -T git@github.com &>/dev/null
  RET=$?
  if [ $RET == 1 ]; then
    # user is authenticated, but fails to open a shell with GitHub 
    return 0
  elif [ $RET == 255 ]; then
    # user is not authenticated
    return 1
  else
    echo "unknown exit code in attempt to ssh into git@github.com"
  fi
  return 2
}
Run Code Online (Sandbox Code Playgroud)

您可以从命令行随意使用它,如下所示:

github-authenticated && echo good
Run Code Online (Sandbox Code Playgroud)

或者更正式地在脚本中,例如:

if github-authenticated; then
    echo "good"
else
    echo "bad"
fi
Run Code Online (Sandbox Code Playgroud)


Von*_*onC 4

“成功验证”消息然后退出 1 可能会令人困惑。
但 GitHub 返回退出状态 1,因为它拒绝执行 ssh 命令所要求的操作:打开交互式 shell。因此'1'

正如ssh 手册页中提到的

ssh 以远程命令的退出状态退出,如果发生错误,则以 255 退出。

有关更多选项,请参阅“如何创建 bash 脚本来检查 SSH 连接? ”。

在你的情况下:

if ssh -q git@github.com; [ $? -eq 255 ]; then
   echo "fail"
else
   # successfully authenticated
fi
Run Code Online (Sandbox Code Playgroud)