我如何在Python中组合这两段代码?

时间:2013-11-06 02:54:07

标签: python email network-monitoring

我想找到一种方法将这两段代码组合成一个函数,当某个服务器出现故障时(即服务器不再接收ping),它会向我发送一封电子邮件。我将如何使用这两个代码段来实现这一目标?

import smtplib
import subprocess
##Ping
    hostname = "x.x.x.x"
    output = subprocess.Popen(["ping.exe",hostname],stdout = subprocess.PIPE).communicate()[0]

    print(output)

    if ('unreachable' in output):
        print("Offline")

##Email
    fromaddr = 'someone@gmail.com'
    toaddrs  = 'somebody@somewhere.com'
    msg = 'Subject: %s\n\n%s' % ('SERVER STATUS', 'Server is Down')
    # Login info
    username = 'user'
    password = 'pass'

    # Outgoing SMTP
    server = smtplib.SMTP('smtp.gmail.com:587')
    server.starttls()
    server.login(username,password)
    server.sendmail(fromaddr, toaddrs, msg,)
    server.quit()

1 个答案:

答案 0 :(得分:1)

只需将其包含在if块中:

import smtplib
import subprocess
##Ping
    hostname = "x.x.x.x"
    output = subprocess.Popen(["ping.exe",hostname],stdout = subprocess.PIPE).communicate()[0]

    print(output)

    if ('unreachable' in output):
        print("Offline")
        fromaddr = 'someone@gmail.com'
        toaddrs  = 'somebody@somewhere.com'
        msg = 'Subject: %s\n\n%s' % ('SERVER STATUS', 'Server is Down')
        # Login info
        username = 'user'
        password = 'pass'

        # Outgoing SMTP
        server = smtplib.SMTP('smtp.gmail.com:587')
        server.starttls()
        server.login(username,password)
        server.sendmail(fromaddr, toaddrs, msg,)
        server.quit()