2

我想找到一种方法将这两段代码组合成一个函数,只要某个服务器出现故障(即服务器不再接收 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()
4

1 回答 1

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()
于 2013-11-06T03:12:18.150 回答