Joined: 24 Sep 2003
|Posted: Fri Jan 05, 2007 11:09 am Post subject: GPG encrypted mails via command line (e.g. for scripting)
|Most admins use shell-scripts which send their outputs as mail-notification, but how can these automatically generated mails be encrypted without interaction?
I needed some hours to find that out, because I didn't find any howtos about that; so here we go:
Let's say we have a script on our server which is executed by root and sends some text output to firstname.lastname@example.org and you are already using GPG (I don't want to write a GPG howto here) and your public key is 12345.
First, you have to install gnupg and mailutils (or mailx or mutt or whatever command line tool you use to send mails) on your server.
Now the root-user from your server has to import your public key (e.g. by gpg --search-keys or gpg --import, see man-page/GPG-howtos for this) and has to set the trust level. You can set it to level 5, you know that it's your key (gpg --edit-key KEY -> command "trust" -> 5). If you don't do this, gpg will nag about no trust level and needs interaction where you have to confirm that you really want to use this key for encryption.
Now you're ready to encrypt your script-generated mails:
script.sh | gpg -e -a -r KEY |mail -s "subject" recipient
echo "This is a GnuPG encrypted test-text" | gpg -e -a -r 12345 |mail -s "test" email@example.com
The trick is to armor the output with -a or else you will have the encrypted rubbish as readable mailtext which is problematic to decode.
If you want to send the output as encrypted attachment, you can do the following:
script.sh | gpg -e -r 12345 > attachment.asc; echo "see attachment" |mutt -a attachment.asc -s "subject" firstname.lastname@example.org
Note: you have to pipe some text to mutt if you want to use it in a script. If you want to have an empty text, just use echo | mutt ...
It is best to use mutt for attachments because otherwise you have to write/modify your mail header, uuencode the attachment etc., which is annoying