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

前端 未结 5 785
隐瞒了意图╮
隐瞒了意图╮ 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条回答
  •  盖世英雄少女心
    2021-01-01 10:24

    keychain

    solves this in a painless way. It's in the repos for Debian/Ubuntu:

    sudo apt-get install keychain
    

    and perhaps for many other distros (it looks like it originated from Gentoo).

    This program will start an ssh-agent if none is running, and provide shell scripts that can be sourced and connect the current shell to this particular ssh-agent.

    For bash, with a private key named id_rsa, add the following to your .profile:

    keychain --nogui id_rsa
    

    This will start an ssh-agent and add the id_rsa key on the first login after reboot. If the key is passphrase-protected, it will also ask for the passphrase. No need to use unprotected keys anymore! For subsequent logins, it will recognize the agent and not ask for a passphrase again.

    Also, add the following as a last line of your .bashrc:

    . ~/.keychain/$HOSTNAME-sh
    

    This will let the shell know where to reach the SSH agent managed by keychain. Make sure that .bashrc is sourced from .profile.

    However, it seems that cron jobs still don't see this. As a remedy, include the line above in the crontab, just before your actual command:

    * * * * * . ~/.keychain/$HOSTNAME-sh; your-actual-command
    

提交回复
热议问题