How to run gpg from a script run by cron?

后端 未结 7 1290
予麋鹿
予麋鹿 2021-02-05 04:10

I have a script that has a part that looks like that:

for file in `ls *.tar.gz`; do
  echo encrypting $file
  gpg --passphrase-file /home/$USER/.gnupg/backup-pas         


        
相关标签:
7条回答
  • 2021-02-05 04:19

    It turns out that the answer was easier than I expected. There is a --batch parameter missing, gpg tries to read from /dev/tty that doesn't exist for cron jobs. To debug that I have used --exit-on-status-write-error param. But to use that I was inspired by exit status 2, reported by echoing $? as Cd-Man suggested.

    0 讨论(0)
  • 2021-02-05 04:19

    In my case gpg cant find home dir for using keys:

    gpg: no default secret key: No secret key

    gpg: 0003608.cmd: sign+encrypt failed: No secret key

    So I added --homedir /root/.gnupg. The final command can looks like

    echo 'password' | gpg -vvv --homedir /root/.gnupg --batch --passphrase-fd 0 --output /usr/share/file.gpg --encrypt --sign /usr/share/file.tar.bz2

    0 讨论(0)
  • 2021-02-05 04:19

    I've came across this problem once.

    I can't really tell you why, but I dont think cron executes with the same environment variable as the user do.

    I actually had to export the good path for my programs to execute well. Is gpg at least trying to execute?

    Or are the files you are trying to encypt actually in the current directory when the cron executes?

    Maybe try to execute a echo whereis gpg and echo $PATH in your script to see if it's included... Worked for me.

    0 讨论(0)
  • 2021-02-05 04:24

    make sure the user that is running the cron job has the permissions needed to encrypt the file.

    0 讨论(0)
  • 2021-02-05 04:26

    In my case: "gpg: decryption failed: Bad session key".

    Tried adding /usr/bin/gpg, checking the version, setting --batch, setting --home (with /root/.gnupg and /home/user/.gnupg) and all did not work.

    /usr/bin/gpg -d --batch --homedir /home/ec2-user/.gnupg --no-mdc-warning -quiet --passphrase "$GPG_PP" "$file"
    

    Turned out that cron on AWS beanstalk instance needed the environment variable being used to set the --passphrase $GPG_PP. Cron now:

    0 15 * * * $(source /opt/elasticbeanstalk/support/envvars && /home/ec2-user/bin/script.sh >> /home/ec2-user/logs/cron_out.log 2>&1)
    
    0 讨论(0)
  • 2021-02-05 04:30

    @skinp Cron jobs are executed by sh, whereas most modern Unixes use bash or ksh for interactive logins. The biggest problem (in my experience) is that sh doesn't understand things like:

    export PS1='\u@\h:\w> '
    

    which needs to be changed to:

    PS1='\u@\h:\w> '
    export PS1
    

    So if cron runs a shell script which defines an environment variable using the first syntax, before running some other command, the other command will never be executed because sh bombs out trying to define the variable.

    0 讨论(0)
提交回复
热议问题