如何将 python 脚本的输出发送到电子邮件地址

发布于 2024-10-21 04:55:49 字数 197 浏览 2 评论 0原文

我有一个线程 python 脚本,可以 ping 局域网上的 20 个节点,并打印出每个节点的状态:节点处于活动状态、节点处于关闭状态等。 我想将此输出发送到我的电子邮件帐户,因为我打算让这个脚本每周运行一次,单独运行,如果我物理上远离局域网,我不必担心,我可以只需查看我的电子邮件即可。

语言:Python。操作系统:Linux Mint 10 Julia。谢谢

I have a threaded python script that pings 20 nodes on a local area network, and prints out the status of each: Node is Alive, Node is Down, etc..
I would like to have this output sent to my email account, Because I intend to make this script to run once a week, on it's own, And if i'm physically away from the lan I won't have to worry, I can just check my email.

Language:PYTHON. OS:Linux Mint 10 Julia. Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

锦欢 2024-10-28 04:55:49

如果它每周运行一次,您可能会从 crontab 运行它?

30 2 * * 5  python yourScript.py | mail -s outputFromScript [email protected]

If it runs once a week, you will probably run it from crontab?

30 2 * * 5  python yourScript.py | mail -s outputFromScript [email protected]
梦行七里 2024-10-28 04:55:49

使用 smtplib。他们提供的 示例 非常好。

import smtplib

def prompt(prompt):
    return raw_input(prompt).strip()

fromaddr = prompt("From: ")
toaddrs  = prompt("To: ").split()
print "Enter message, end with ^D (Unix) or ^Z (Windows):"

# Add the From: and To: headers at the start!
msg = ("From: %s\r\nTo: %s\r\n\r\n"
       % (fromaddr, ", ".join(toaddrs)))
while True:
    try:
        line = raw_input()
    except EOFError:
        break
    if not line:
        break
    msg += line

print "Message length is " + repr(len(msg))

server = smtplib.SMTP('localhost')
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()

Use smtplib. The example they provide is pretty good.

import smtplib

def prompt(prompt):
    return raw_input(prompt).strip()

fromaddr = prompt("From: ")
toaddrs  = prompt("To: ").split()
print "Enter message, end with ^D (Unix) or ^Z (Windows):"

# Add the From: and To: headers at the start!
msg = ("From: %s\r\nTo: %s\r\n\r\n"
       % (fromaddr, ", ".join(toaddrs)))
while True:
    try:
        line = raw_input()
    except EOFError:
        break
    if not line:
        break
    msg += line

print "Message length is " + repr(len(msg))

server = smtplib.SMTP('localhost')
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
要走就滚别墨迹 2024-10-28 04:55:49

您可以使用 logger 来打印到 stout 和记录器,而不是使用主 print 输出。

您可以根据 Logging Cookbook

import logging
log_file = r'C:\Users\user\Downloads\LogFileName.log'

logger = logging.getLogger('simple_example')
logger.setLevel(logging.INFO)

# create file handler which logs even debug messages
fh = logging.FileHandler('log_file')
fh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
fh.setFormatter(formatter)
# add the handlers to logger
logger.addHandler(ch)
logger.addHandler(fh)

现在替换脚本中的 print使用 logger.info

之前的示例:

print("Printing status")

之后的示例:

logger.info("Printing status")

然后您可以将日志通过电子邮件发送给自己,如下所示:

import smtplib
from email.message import EmailMessage
import os
msg_body = "Body Text"

msg = EmailMessage()

msg['Subject'] = "Subject"
msg['From'] = "[email protected]"
msg['To'] = "[email protected]"

msg.set_content(msg_body)

if os.path.isfile(log_file):
        msg.add_attachment(open(log_file, "r").read(), filename=os.path.basename(log_file))


# Send the message via our own SMTP server.
s = smtplib.SMTP("smtpa.server")
s.send_message(msg)
s.quit()

Instead of having your main print the output, you could use a logger to print to stout and to the logger

You can set up a logger as follows according to the Logging Cookbook:

import logging
log_file = r'C:\Users\user\Downloads\LogFileName.log'

logger = logging.getLogger('simple_example')
logger.setLevel(logging.INFO)

# create file handler which logs even debug messages
fh = logging.FileHandler('log_file')
fh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
fh.setFormatter(formatter)
# add the handlers to logger
logger.addHandler(ch)
logger.addHandler(fh)

Now in replace print in your script with logger.info

Example before:

print("Printing status")

Example after:

logger.info("Printing status")

Then you can email the log to yourself as follows:

import smtplib
from email.message import EmailMessage
import os
msg_body = "Body Text"

msg = EmailMessage()

msg['Subject'] = "Subject"
msg['From'] = "[email protected]"
msg['To'] = "[email protected]"

msg.set_content(msg_body)

if os.path.isfile(log_file):
        msg.add_attachment(open(log_file, "r").read(), filename=os.path.basename(log_file))


# Send the message via our own SMTP server.
s = smtplib.SMTP("smtpa.server")
s.send_message(msg)
s.quit()
浅笑依然 2024-10-28 04:55:49

看一下logging和logging.config,我之前用过它从后台运行的脚本接收错误消息

http://docs.python.org/library/logging.html

例如

import logging
import logging.config

logDir = "./logs/"

logging.config.fileConfig(logDir+'logging.conf')
logger = logging.getLogger('email')

logger.debug('THIS IS A DEBUG MESSAGE')
logger.error('THIS IS AN ERROR')

然后是logging.conf

[loggers]
keys=root,email

[logger_root]
level=DEBUG
handlers=rotatingFileHandler

[logger_email]
level=ERROR
handlers=email
qualname=email

[formatters]
keys=emailFormatter,rotatingFormatter

[formatter_emailFormatter]
format=%(asctime)s %(name)-12s %(levelname)-8s %(message)s

[formatter_rotatingFormatter]
format=%(asctime)s %(name)-12s %(levelname)-8s %(message)s
datefmt=%m-%d %H:%M

[handlers]
keys=email,rotatingFileHandler

[handler_email]
class=handlers.SMTPHandler
level=ERROR
formatter=emailFormatter
args=('mail.xxx','[email protected]',['[email protected]',],'ERROR!',('[email protected]','xxx'))

[handler_rotatingFileHandler]
class=handlers.RotatingFileHandler
level=DEBUG
formatter=rotatingFormatter
args=('./logs/log.out', 'maxBytes=1000000', 'backupCount=5')

从上面我会在我的电子邮件中收到“这是一个错误”。

Take a look at the logging and logging.config, I've used this before to receive error messages from a script running in the background

http://docs.python.org/library/logging.html

For example

import logging
import logging.config

logDir = "./logs/"

logging.config.fileConfig(logDir+'logging.conf')
logger = logging.getLogger('email')

logger.debug('THIS IS A DEBUG MESSAGE')
logger.error('THIS IS AN ERROR')

And then the logging.conf

[loggers]
keys=root,email

[logger_root]
level=DEBUG
handlers=rotatingFileHandler

[logger_email]
level=ERROR
handlers=email
qualname=email

[formatters]
keys=emailFormatter,rotatingFormatter

[formatter_emailFormatter]
format=%(asctime)s %(name)-12s %(levelname)-8s %(message)s

[formatter_rotatingFormatter]
format=%(asctime)s %(name)-12s %(levelname)-8s %(message)s
datefmt=%m-%d %H:%M

[handlers]
keys=email,rotatingFileHandler

[handler_email]
class=handlers.SMTPHandler
level=ERROR
formatter=emailFormatter
args=('mail.xxx','[email protected]',['[email protected]',],'ERROR!',('[email protected]','xxx'))

[handler_rotatingFileHandler]
class=handlers.RotatingFileHandler
level=DEBUG
formatter=rotatingFormatter
args=('./logs/log.out', 'maxBytes=1000000', 'backupCount=5')

From the above I would receive "THIS IS AN ERROR" in my email.

只等公子 2024-10-28 04:55:49

Al Sweigart 的“用 Python 自动化无聊的工作”是关于使用 Python 发送电子邮件主题的一个很好的资源。 第 18 章 是您想要的部分。简而言之,如果您有一个大型电子邮件提供商(例如 Google、Outlook、Yahoo 等)的电子邮件地址,您可以使用他们的简单邮件传输协议 (SMTP) 服务器来处理来自 Python 的消息。正如 Al 所说:

在此处输入图像描述

如果您没有大型提供商的电子邮件地址,或者您无法使用外部提供商的电子邮件地址,那么这是一个难一点。也许您公司的某个人可以告诉您 1) 您的公司是否有 SMTP 服务器以及 2) 它的域名和端口号是什么。

一旦你拥有了所有这些,从你的程序发送一封电子邮件就是小菜一碟:

import smtplib

def main():

    # get message from node
    message1 = 'Node 1 is up :)'
    # print message from node
    print(message1)
    # get message from another node
    message2 = 'Node 2 is down :('
    # print that too
    print(message2)

    # now, all done talking to nodes.
    # time to compile node response results and send an email.

    # first, let's get every thing setup for the email
    from_me = 'awesome.name@my_email_provider.com'
    to_me = 'awesome.name@my_email_provider.com'
    email_message = message1 + '\n' + message2

    # second, let's make sure we have a connection to a Simple Mail Transfer Protocol (SMTP) server 
    # this server will receive and then send out our email message
    domain_name = 'smtp.my_email_provider.com'
    port_number = 587  # or maybe, 465
    server = smtplib.SMTP(domain_name, port_number)

    # alright! if that last line didn't raise an exceptions, then you're good to go. Send that bad boy off.
    server.sendmail(from_me, to_me, email_message)

if __name__ == '__main__':
    main()

记录器也很棒,所以不要低估每个人对它们的评价。
打印到终端。记录到文件。并通过电子邮件发出!记录仪可以做一切事情。

A great resource on the topic of sending email with Python is Al Sweigart's 'Automate the Boring Stuff with Python'. Chapter 18 is the part you want. In short, if you have an email address with one of the big email providers (think Google, Outlook, Yahoo, etc.) you can use their Simple Mail Transfer Protocol (SMTP) server(s) to handle your messages from Python. As Al says:

enter image description here

If you don't have an email address with one of the big providers or you're not in a position where you can use an email address from an outside provider, then it's a bit harder. Perhaps someone at your company can tell you 1) if your company has an SMTP server and 2) what its domain name and port number are.

Once you have all that, sending out an email message from your program is a piece of cake:

import smtplib

def main():

    # get message from node
    message1 = 'Node 1 is up :)'
    # print message from node
    print(message1)
    # get message from another node
    message2 = 'Node 2 is down :('
    # print that too
    print(message2)

    # now, all done talking to nodes.
    # time to compile node response results and send an email.

    # first, let's get every thing setup for the email
    from_me = 'awesome.name@my_email_provider.com'
    to_me = 'awesome.name@my_email_provider.com'
    email_message = message1 + '\n' + message2

    # second, let's make sure we have a connection to a Simple Mail Transfer Protocol (SMTP) server 
    # this server will receive and then send out our email message
    domain_name = 'smtp.my_email_provider.com'
    port_number = 587  # or maybe, 465
    server = smtplib.SMTP(domain_name, port_number)

    # alright! if that last line didn't raise an exceptions, then you're good to go. Send that bad boy off.
    server.sendmail(from_me, to_me, email_message)

if __name__ == '__main__':
    main()

Loggers are great too, so don't discount what everyone's said about them.
Print to the terminal. Log to a file. AND email out! Loggers can do everything.

划一舟意中人 2024-10-28 04:55:49

您需要一个 SMTP 服务器来发送电子邮件。查看 Python 的 smtplib

You need a SMTP server to send Email. Check out the smtplib for Python

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文