如何组合python脚本

时间:2018-04-22 07:34:30

标签: python

我在各个网站上找到了这些代码:ping.pyconf.py。它工作正常。我需要将这些文件合并到一个文件中。

ping.py

#!/usr/bin/env python

import smtplib
import pyping
from conf import settings, sites
import time
import datetime

"""Sends an e-mail to the specified recipient."""
sender = settings["monitor_email"]
recipient = settings["recipient_email"]
subject = settings["email_subject"]
headers = ["From: " + sender,
    "Subject: " + subject,
    "To: " + recipient,
    "MIME-Version: 1.0",
    "Content-Type: text/html"]
headers = "\r\n".join(headers)
session = smtplib.SMTP(settings["monitor_server"],
settings["monitor_server_port"])
session.ehlo()
session.login(settings["monitor_email"], settings["monitor_password"])
ts = time.time()
st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')

   for site in sites:
   checker = pyping.ping(site)
   # The site status changed from it's last value, so send an email

   if checker.ret_code == 0:

    # The site is UP
    body = "%s This Server is up %s" % (site, st)
    session.sendmail(sender, recipient, headers + "\r\n\r\n" + body)
else:
    # The site is Down
    body = "%s This Server is down %s" % (site, st)
    session.sendmail(sender, recipient, headers + "\r\n\r\n" + body)

  session.quit()

conf.py

sites = (
"192.168.1.1",
"192.168.2.1",
"192.168.3.1",
)

settings = {
"recipient_email": 'tomail@domain.com',
"monitor_email": 'frommail@domain.com',
"monitor_password": 'password',

# Leave as it is to use gmail as the server
"monitor_server": 'frommail@domain.com',
"monitor_server_port": 587,

# Optional Settings
"email_subject": 'Server Monitor Alert'
}

如何将conf.py集成到ping.py中,以便我可以通过运行单个文件获得输出?

2 个答案:

答案 0 :(得分:2)

您需要复制整个文件,因为"recipient_email": 'tomail@domain.com'不是有效的变量定义。

from conf import settings, sites替换为文件内容,或者更好,根据需要定义变量。

例如,而不是

sender = settings["monitor_email"]
recipient = settings["recipient_email"]
subject = settings["email_subject"]

sender = "frommail@domain.com"
recipient = "tomail@domain.com"
subject = 'Server Monitor Alert'
# TODO: Define other values
  

当我把recipient = tomail@gmail.com放入其中时

你需要围绕字符串变量引用...

答案 1 :(得分:1)

conf.py的完整内容复制并粘贴到<{p>之后的ping.py

import datetime

线。然后删除行

from conf import settings, sites

来自ping.py

请注意,这样做通常与您在良好编码风格方面应该做的完全相反。通常,您希望模块化您的代码,而这意味着采用(或多或少)模块化代码并将其变成一个庞大而笨拙的团块。