简体   繁体   中英

Misuse of shell builtins when adding an ssh key using ssh-add

I have a script.sh file which checks for loaded SSH agent and adds a key.

If I run this script directly, it works but if I run it via some worker it doesn't unless I do those changes:

This works:

#!/bin/bash -e

printf "<<<<< Start SSH agent and Github deploy key >>>>>\n"
if ps -p $SSH_AGENT_PID > /dev/null
then
  printf "<<<<< ssh-agent is already running >>>>>\n"
else
  eval `ssh-agent -s`
fi
ssh-add $deploy_key_path

But his doesn't work:

#!/bin/bash -e

if [ $(ps ax | grep [s]sh-agent | wc -l) -gt 0 ] ; then
  printf "<<<<< ssh-agent is already running >>>>>\n"
else
  eval `ssh-agent -s`
fi
ssh-add $deploy_key_path

The error says ...failed. Exit Code: 2(Misuse of shell builtins).. ...failed. Exit Code: 2(Misuse of shell builtins).. which happens at the line ssh-add $deploy_key_path

When checking the reserved Bash error codes I see:

2   Misuse of shell builtins    empty_function() {} Missing keyword or command

Here is one reasonable way I'd use ssh-agent and ssh-add , minimizing security risks by not keeping keys unlocked more than it is strictly needed within the script.

#!/usr/bin/env sh

# Do not leave key unlocked after execution of this script
trap 'ssh-add -d "$deploy_key_path"' EXIT INT

# If ssh-agent has an auth socket or has a PID
if [ -S "$SSH_AUTH_SOCK" ] || ps -p "$SSH_AGENT_PID" >/dev/null 2>&1; then
  printf '<<<<< ssh-agent is already running >>>>>\n'
else
  # Do not use back-ticks as it is legacy obsolete
  eval "$(ssh-agent -s)"
fi

# Do not leave key unlocked more than 5 minutes
ssh-add -t 600 "$deploy_key_path"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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