Linux cron job to email output from a command

南楼画角 提交于 2019-12-12 02:10:17

问题


I would like to run a cron job to backup some mysql databases by piping the output to a file and then emailing it.

Will the following work?

15 2 * * * root mysqldump -u root -pPASSWORD --all-databases | \
    gzip > /database_`data'+%m-%d-%Y'`.sql.gz | \
    mail -s "Report 05/06/07" user@example.com < /database_`data'+%m-%d-%Y'`.sql.gz

回答1:


There are a couple of problems with your script, I have altered it below, note carefully the change of spaces, spelling of date and replacement of | for ;.

The most interesting problem however is that mail unfortunately can't send attachments. You could use uuencode to embed the file in the mail using:

15 2 * * * root mysqldump -uroot -pPASSWORD --all-databases | gzip > /database_`date +'%m-%d-%Y'`.sql.gz ; uuencode /database_`date +'%m-%d-%Y'`.sql.gz /dev/stdout | mail -s "Report 05/06/07" user@domain.com

Or if you want to have a proper MIME attachment use (You will need MetaMail installed):

15 2 * * * root mysqldump -uroot -pPASSWORD --all-databases | gzip > /database_`date +'%m-%d-%Y'`.sql.gz ; metasend -b -t user@domain.com -s "Report 05/06/07" -m application/gzip -f /database_`date +'%m-%d-%Y'`.sql.gz

Or as above with mpack installed, instead of MetaMail:

15 2 * * * root mysqldump -uroot -pPASSWORD --all-databases | gzip > /database_`date +'%m-%d-%Y'`.sql.gz ; mpack -s "Report 05/06/07" -c application/gzip /database_`date +'%m-%d-%Y'`.sql.gz user@domain.com



回答2:


I've tried the first option but had an error, with a small modification it worked fine:

15 2 * * * root mysqldump -e --user=root --password=PASSWORD --all-databases | gzip | uuencode `date +'%Y%m%d'`-database.sql.gz | mail -s "`date +'%Y%m%d'`-web1_iepe-wp.sql.gz mysqldump backup" user@domain.com

Tks!



来源:https://stackoverflow.com/questions/5190215/linux-cron-job-to-email-output-from-a-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!