2011-03-09 18 views
1

私はローカルエリアネットワークで20ノードのpingを実行し、各ノードのステータスを出力します:ノードはアライブ、ノードはダウンしています。 私はこの出力を自分のメールアカウントに送りたいと思っています。私はこのスクリプトを週に1回実行するつもりなので、それは自分のものです。そして、物理的に離れていても心配する必要はありません。私の電子メールをちょうどチェックできます。pythonスクリプトの出力を電子メールアドレスに送信する方法

言語:PYTHON。 OS:Linux Mint 10 Julia。ありがとう

+0

あなたはどのプラットフォームにいますか? –

答えて

5

smtplibを使用してください。彼らが提供するexampleはかなり良いです。

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 1: 
    try: 
     line = raw_input() 
    except EOFError: 
     break 
    if not line: 
     break 
    msg = msg + line 

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

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

電子メールを送信するにはSMTPサーバーが必要です。 smtplib(Python用)

6

週に1回実行すると、おそらくcrontabから実行されますか?バックグラウンドで実行中のスクリプトからのエラーメッセージを受信する前に、

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

あなたはおそらく、 "|"を使ってパイプに詰め込みたいのですが、スペースで区切られたファイルにリダイレクトするのではなく(cronがコマンドラインをどのように解釈するかに依存します)、それは賢明で賢明な考え方です。 – Vatine

+1

@Vatine - あなたはパイプで絶対に正しいです、ありがとう、固定! – eumiro

+0

クール、私の+1はすでに与えられていますが、私はあなたにとても素早く編集を行うためのあなたのコメントのために1つを与えます。 – Vatine

0

ロギングと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') 

上記より、私のメールには「これはエラーです」と表示されます。

関連する問題