小白的linux笔记8:linux自动运行爬虫并发送提醒邮件

有了成功运行的爬虫后,希望能每天定时运行,且遇到错误时能及时发出提醒。

发出提醒

可以用mailx发出邮件做提醒。没有的话先安装Yum install mailx。

以qq邮箱为例,需要设置/etc/mail.rc,增加以下行:

1 set smtp=smtp.qq.com
2 set smtp-auth=login
3 set smtp-auth-user=user@qq.com
4 set smtp-auth-password=code  //不是登录密码,是stmp的授权密码
5 set ssl-verify=ignore
6 set nss-config-dir=/etc/pki/nssdb  //没有的话需要mkdir新建
7 set from="user@qq.com(nickname)"
8 set smtp-use-starttls=yes

同时还需要在qq邮箱中开启IMAP/STMP,并获得授权码:

在邮箱设置-账户-POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务中打开相关选项。

测试一下:mail xxx@aa.com,然后在subjuct后输入主题,回车输入内容,完事后输入.回车。发送成功。

或者:echo '邮件内容' | mail -s '邮件标题' 收件人邮箱。

或者:cat 邮件内容.txt | mail -s '邮件标题' 收件人邮箱

或者:mail -s '邮件标题' 收件人邮箱 < 邮件内容.txt

https://blog.csdn.net/yongren_z/article/details/85119088

https://www.cnblogs.com/huyihao/p/5543125.html

开始用outlook设置,折腾了半天还是失败,而且每次登陆都好慢,干脆放弃了。

还有一个选择是发微信,有空可以再研究一下。http://sc.ftqq.com/3.version

https://blog.csdn.net/qq_19645105/article/details/90173867

写BASH

 1 #!/bin/bash
 2 workpath="/home/share/scraping/getlj"
 3 cd $workpath
 4 # 进入工作目录
 5 python3 0-save_todaylj.py 2>2-getlj_err.txt
 6 # 输出错误文件
 7 
 8 todaydate=$(date +%F)
 9 # 测试err文件中有无内容,如有发送提醒
10 if [ -s $workpath/2-getlj_err.txt ];then
11     # `pwd`/getlj_err.txt也可,pwd=当前工作目录
    # -s等同于test -s测试是否存在文件且不为空,有非空则返回TRUE,在这里意味着有error记录
12 echo $todaydate:error 13 cat '2-getlj_err.txt' | mail -s "$todaydate getlj ERROR" cityfxckr@qq.com 14 else 15 echo $todaydate:ok 16 cat '1-ljszresult.txt' | mail -s "$todaydate getlj RESULT" cityfxckr@qq.com 17 fi 18 19 # 邮件主题中包含变量时,一定要用双引号才行 20 # 需要将此段代码转换成linux模式即每行结尾只有 (LF),而windows模式是 (CRLF)运行会报错,
   notepad++的编辑-文档格式转换中可以转换
21 # 发送邮件的内容,此例中的txt文件,同样需要时linux模式,否则不会再正文发送,而会变成一个bin格式的附件

邮件主题中变量的设置:

https://stackoverflow.com/questions/20535024/how-to-insert-the-current-date-in-mail-command-in-linux

https://unix.stackexchange.com/questions/383722/adding-date-to-file-name-when-sending-email

https://stackoverflow.com/questions/35920673/sending-mail-with-subject-as-variable

test命令的使用:

https://www.jianshu.com/p/6d55b6c0f350

https://man.linuxde.net/test

https://linuxize.com/post/bash-check-if-file-exists/

if记得要有fi结尾。

定时运行

需要用到crontab功能。https://www.cnblogs.com/ftl1012/p/crontab.html

修改etc/crontab文件,增加要定时运行的程序,并将运行输出记录到runlog.txt中:

0 8 * * * wts . /home/0-rungetlj.sh>>/home/2-runlog.txt /etc/cron.daily

(关于linux的运行级别:https://blog.csdn.net/ltstud/article/details/78683523)

 

成功,这样每天就可以收到抓取的结果,或者是出现的错误以便及时修改。

原文地址:https://www.cnblogs.com/cityfckr/p/12330276.html