【问题标题】:how to email the output file attachment of the shell script thru python script using cron automatically?如何使用cron自动通过python脚本通过电子邮件发送shell脚本的输出文件附件?
【发布时间】:2018-10-04 04:16:01
【问题描述】:

我有 2 个脚本(1 个是运行 shell 脚本,1 个是用于发送电子邮件的 python 脚本)。现在我想使用 cron 自动通过 python 发送文件附件的输出...

【问题讨论】:

  • 嗨,请参考这个页面来询问通常会被投票的好问题,这有助于获得好的答案How do I ask a good question?
  • @Karthik,当你问问题时要清楚,你尝试了什么,你的代码是什么样的,现在预期什么不起作用等等。我刚刚发布了一个基于我的答案明白了。

标签: python python-2.7 shell python-requests


【解决方案1】:

这是python发送电子邮件的一种方式:

#!/usr/bin/python
from subprocess import Popen, PIPE
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import os
import smtplib

############ File comparison & sendmail part starts here ########
def ps_Mail():
    filename = "/tmp/ps_msg"  # this is your file path you want to sent
    filename = open(filename)
    if os.path.exists(filename) and os.path.getsize(filename) > 0:
        mailp = Popen(["/usr/sbin/sendmail", "-t", "-oi"], stdin=PIPE)
        msg = MIMEMultipart()
        msg['To'] = "user@example.com"
        msg['Subject'] = "My Test E-mail"
        msg['From'] = "some_user@example.com"
        msg1 = MIMEText(filename.read(),  'text')
        msg.attach(msg1)
        mailp.communicate(msg.as_string())
ps_Mail()

关于设置 cronjob 尝试如下:

a) 如果它是一个 shell 脚本,然后像下面这样运行它..,编辑 crontab-e 参数

$ crontab -e
*/30 * * * * /home/script/myfile.sh

保存文件,您就可以用餐了..

b) 如果它的 python & 你想每 30 分钟运行一次这个脚本。

*/30 * * * * /usr/bin/python script.py

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 2012-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-04
    • 2013-07-07
    相关资源
    最近更新 更多