Why ssh fails from crontab but succedes when executed from a command line?

前端 未结 5 770
隐瞒了意图╮
隐瞒了意图╮ 2021-01-01 09:41

I have a bash script that does ssh to a remote machine and executes a command there, like:

ssh -nxv user@remotehost echo \"hello world\"

Wh

5条回答
  •  旧时难觅i
    2021-01-01 10:07

    So I had a similar problem. I came here and saw various answers but with some experimentation here is how I got it work with sshkeys with passphrase, ssh-agent and cron.

    First off, my ssh setup uses the following script in my bash init script.

    # JFD Added this for ssh
    SSH_ENV=$HOME/.ssh/environment
    
        # start the ssh-agent
        function start_agent {
            echo "Initializing new SSH agent..."
            # spawn ssh-agent
            /usr/bin/ssh-agent | sed 's/^echo/#echo/' > "${SSH_ENV}"
            echo succeeded
            chmod 600 "${SSH_ENV}"
            . "${SSH_ENV}" > /dev/null
            /usr/bin/ssh-add
        }
    
    
        if [ -f "${SSH_ENV}" ]; then
             . "${SSH_ENV}" > /dev/null
             ps -ef | grep ${SSH_AGENT_PID} | grep ssh-agent$ > /dev/null || {
                start_agent;
            }
       else
            start_agent;
       fi
    

    When I login, I enter my passphrase once and then from then on it will use ssh-agent to authenticate me automatically.

    The ssh-agent details are kept in .ssh/environment. Here is what that script will look like:

    SSH_AUTH_SOCK=/tmp/ssh-v3Tbd2Hjw3n9/agent.2089; export SSH_AUTH_SOCK;
    SSH_AGENT_PID=2091; export SSH_AGENT_PID;
    #echo Agent pid 2091;
    

    Regarding cron, you can setup a job as a regular user in various ways. If you run crontab -e as root user it will setup a root user cron. If you run as crontab -u davis -e it will add a cron job as userid davis. Likewise, if you run as user davis and do crontab -e it will create a cron job which runs as userid davis. This can be verified with the following entry:

    30 *  *   *   *     /usr/bin/whoami
    

    This will mail the result of whoami every 30 minutes to user davis. (I did a crontabe -e as user davis.)

    If you try to see what keys are used as user davis, do this:

    36 *  *   *   *     /usr/bin/ssh-add -l
    

    It will fail, the log sent by mail will say

    To: davis@xxxx.net
    Subject: Cron  /usr/bin/ssh-add -l
    
    Could not open a connection to your authentication agent.
    

    The solution is to source the env script for ssh-agent above. Here is the resulting cron entry:

    55 10  *   *   *     . /home/davis/.ssh/environment; /home/davis/bin/domythingwhichusesgit.sh
    

    This will run the script at 10:55. Notice the leading . in the script. It says to run this script in my environment similar to what is in the .bash init script.

提交回复
热议问题