Exemplo n.º 1
0
 def executeImport(cls, conn, importFile, **params):
     tokenValue = conn.authorization
     workspaceId = conn.workspaceGuid
     modelId = conn.modelGuid
     # Get the list of imports and choose one with the importId and the datasourceId
     print('IMPORT001 - %s - Retrieving the list of imports' % (importFile))
     importInfos = cls.getImportInfo(tokenValue, workspaceId, modelId,
                                     importFile)
     print("IMPORT002 - %s - Import ID retrieved" % (importFile))
     importId = importInfos[0]
     # # Trigger the import
     print("IMPORT005 - %s - Executing the Import" % (importFile))
     executeImport = cls.importTrigger(tokenValue, workspaceId, modelId,
                                       importId, **params)
     print("IMPORT006 - %s - Import Triggered" % (importFile))
     # # Get the status of the import
     print("IMPORT007 - %s - Checking status of import" % (importFile))
     url = urlStem + "/workspaces/" + workspaceId + "/models/" + modelId + "/imports/" + importId + "/tasks"
     post_header = {
         'Authorization': 'AnaplanAuthToken %s' % tokenValue,
         'Content-Type': 'application/json'
     }
     checkStatusImport = check_status(url, executeImport, post_header)
     print("IMPORT008 - %s - Status Retrieved" % (importFile))
     emailSubject = "Anaplan Execution - " + importFile
     emailText = checkStatusImport
     sendemail.sendEmail(emailSubject, emailText)
Exemplo n.º 2
0
def SendEmail():
	while True:
		item = emailque.get()
		tousrs = ['*****@*****.**','*****@*****.**','*****@*****.**',\
				'*****@*****.**','*****@*****.**','*****@*****.**',\
				'*****@*****.**','*****@*****.**','*****@*****.**']
		sendEmail(item.emailtitle,tousrs,'web API errors',item.errmsg)
Exemplo n.º 3
0
def shutdownPi(why):
    """Shutdown Pi."""
    pclogging.log(pclogging.INFO, __name__, "Pi Shutting Down: %s" % why)
    sendemail.sendEmail("test", "WeatherPi Shutting down:" + why, "The WeatherPi Raspberry Pi shutting down.", conf.notifyAddress,  conf.fromAddress, "")
    sys.stdout.flush()
    time.sleep(10.0)
    os.system("sudo shutdown -h now")
Exemplo n.º 4
0
def reboot_and_wdcp(comm='reboot'):
    print("尝试重启服务器....")
    save_log("尝试重启服务器....")
    check_service(comm=comm)
    time.sleep(30)

    print("正在开启wdcp服务....")
    save_log("正在开启wdcp服务....")
    check_service(comm="sh /www/wdlinux/wdcp/wdcp.sh start")
    time.sleep(30)

    result, result_msg = check_mysql()

    if not result:
        print("重启服务器都不行,再次check mysql")
        save_log(link + "重启服务器都不行,再次check mysql" + result_msg)
        sendemail.title = link + ",重启服务器都不行,再次check mysql"
        sendemail.content = result_msg
        sendemail.sendEmail()
        time.sleep(50)
        result, result_msg = check_mysql()
        if result:
            return True
        else:
            return reboot_and_wdcp()
    else:
        print(link + "重启服务器成功")
        save_log(link + ",重启服务器成功" + result_msg)
        sendemail.title = link + "重启服务器成功"
        sendemail.content = result_msg
        sendemail.sendEmail()
        return True
Exemplo n.º 5
0
def shutdownPi(why):

   pclogging.log(pclogging.INFO, __name__, "Pi Shutting Down: %s" % why)
   sendemail.sendEmail("test", "WeatherPi Shutting down:"+ why, "The WeatherPi Raspberry Pi shutting down.", conf.notifyAddress,  conf.fromAddress, "");
   sys.stdout.flush()
   time.sleep(10.0)

   os.system("sudo shutdown -h now")
Exemplo n.º 6
0
def shutdownPi(why):

    pclogging.systemlog(config.INFO, "Pi Shutting Down: %s" % why)
    sendemail.sendEmail("test", "SkyWeather2 Shutting down:" + why,
                        "The SkyWeather2 Raspberry Pi shutting down.",
                        config.notifyAddress, config.fromAddress, "")
    sys.stdout.flush()
    time.sleep(10.0)

    os.system("sudo shutdown -h now")
Exemplo n.º 7
0
def takeAndSendPicture(source, pwm, pan, tilt ):
	
	#try:
       	exposure = takeRaspiStill(source,pwm, pan, tilt)
		
       	bodyText =  "\n" + "BV=%0.2fV/BC=%0.2fmA/SV=%0.2fV/SC=%0.2fmA/%s" % (batteryVoltage, batteryCurrent, solarVoltage, solarCurrent,exposure)

	sendemail.sendEmail("TestPicture", bodyText, "Project Curacao2 Picture \n", config.notifyAddress,  config.fromAddress, "static/picamera.jpg")
	#except:
       	#print "Camera Failed"

	return
Exemplo n.º 8
0
def executeRemoteCommand(command):
    result = True
    
    if command == REMOTE_LOCK:
        if hardwareconfig.checkLock() == False:
            AFroutines.lockScreen()
            result = sendemail.sendEmail("Command successful","Screen locked")
            eventQueue.put(("Log",'Screen locked due to remote command'))
        else:
            eventQueue.put(("Log",'Lock screen failed - command received while locked'))
            result = sendemail.sendEmail("Command failed","Screen already locked")
            
    elif command == REMOTE_STARTMONITOR:
        #cant check ispy camera status, just have to assume it was not monitoring
        iSpyPath = fileconfig.config.get('TRIGGERS','ispy_path')
        roomCamID = fileconfig.config.get('TRIGGERS','room_cam_id')
        if os.path.exists(iSpyPath):
            eventQueue.put(("Log","Starting room camera due to remote command"))
        else:
            eventQueue.put(("Log","iSpy executable not found - cannot fulfill remote command"))
            return
        
        subprocess.call([iSpyPath,'commands bringonline,2,%s'%roomCamID])
        result = sendemail.sendEmail("Command successful","Movement monitoring initiated. Have a nice day.")
        
    elif command == REMOTE_STOPMONITOR:
        #cant check ispy camera status, just have to assume it was already monitoring
        iSpyPath = fileconfig.config.get('TRIGGERS','ispy_path')
        roomCamID = fileconfig.config.get('TRIGGERS','room_cam_id')
        if os.path.exists(iSpyPath):
            eventQueue.put(("Log","Stopping room camera due to remote command"))
        else:
            eventQueue.put(("Log","iSpy executable not found - cannot fulfill remote command"))
            return
            
        subprocess.call([iSpyPath,'commands takeoffline,2,%s'%roomCamID])
        result = sendemail.sendEmail("Command successful","Movement monitoring disabled. Welcome home!")
        
    elif command == REMOTE_SHUTDOWN:
        result = sendemail.sendEmail("Command successful","Shutting down...")
        eventQueue.put(("Log","Initiating standard shutdown due to remote command"))
        AFroutines.standardShutdown()
        
    elif command == REMOTE_KILLSWITCH:
        eventQueue.put(("Log","Initiating emergency shutdown due to remote command"))
        AFroutines.emergency()
        
    if result != True: eventQueue.put(('Log','Mail send failed: %s'%result))
Exemplo n.º 9
0
def init_sys():
    #declare the sensor, mail system and reference value
    global ths
    global p
    global se
    global sendflag
    global temp_max_ref
    global temp_min_ref
    global humid_max_ref
    global humid_min_ref
    #initialize the detect value
    global pir_detect
    pir_detect = False
    global temp
    temp = -300
    global humid
    humid = -1
    #initialize the whole system, including the sensor, mail system and reference value
    ths = temp_detect.temp_hum_sensor(13)
    p = pir.pir(19)
    se = sendemail.sendEmail('*****@*****.**')
    temp_max_ref = config.max_temp
    temp_min_ref = config.min_temp
    humid_max_ref = config.max_humid
    humid_min_ref = config.min_humid
    print(str(humid_min_ref))
    sendflag = False
Exemplo n.º 10
0
 def executeProcess(cls, conn, processName, **params):
     tokenValue = conn.authorization
     workspaceId = conn.workspaceGuid
     modelId = conn.modelGuid
     # Get the list of imports and choose one with the importId and the datasourceId
     print("PROC001 - %s - Retrieving the list of imports" %(processName))
     processInfos = cls.getProcessInfo(tokenValue, workspaceId, modelId, processName)
     processId = processInfos
     print("PROC002 - %s - Import ID retrieved. See below:" %(processName))
     # # Trigger the import
     print("PROC003 - %s - Executing the Process" %(processName))
     print(params)
     executeImport = cls.execute_action_with_parameters(conn, processId, 3, **params)
     print("PROC004 - %s - Process Executed" %(processName))
     # # Get the status of the import
     emailSubject = "Anaplan Execution - " + processName
     emailText = executeImport
     sendemail.sendEmail(emailSubject, emailText)
Exemplo n.º 11
0
def process_as3935_interrupt():

    global as3935Interrupt
    global as3935, as3935LastInterrupt, as3935LastDistance, as3935LastStatus

    as3935Interrupt = False

    print "processing Interrupt from as3935"
    # turn I2CBus 0 on
    #tca9545.write_control_register(TCA9545_CONFIG_BUS0)
    # turn I2CBus 2 on
    tca9545.write_control_register(TCA9545_CONFIG_BUS2)
    time.sleep(0.003)
    reason = as3935.get_interrupt()

    as3935LastInterrupt = reason

    if reason == 0x00:
        as3935LastStatus = "Spurious Interrupt"
    elif reason == 0x01:
        as3935LastStatus = "Noise Floor too low. Adjusting"
        as3935.raise_noise_floor()
    elif reason == 0x04:
        as3935LastStatus = "Disturber detected - masking"
        as3935.set_mask_disturber(True)
    elif reason == 0x08:
        now = datetime.now().strftime('%H:%M:%S - %Y/%m/%d')
        distance = as3935.get_distance()
        as3935LastDistance = distance
        as3935LastStatus = "Lightning Detected " + str(
            distance) + "km away. (%s)" % now
        pclogging.log(
            pclogging.INFO, __name__,
            "Lightning Detected " + str(distance) + "km away. (%s)" % now)
        sendemail.sendEmail("test", "WeatherPi Lightning Detected\n",
                            as3935LastStatus, conf.textnotifyAddress,
                            conf.textfromAddress, "")

    print "Last Interrupt = 0x%x:  %s" % (as3935LastInterrupt,
                                          as3935LastStatus)
    tca9545.write_control_register(TCA9545_CONFIG_BUS0)

    time.sleep(0.003)
Exemplo n.º 12
0
def restart_mysql(comm='systemctl restart mysqld.service'):
    print("mysql服务挂了,正在重试....")
    save_log("mysql服务挂了,正在重试....")
    check_service(comm=comm)
    service_result, service_log = check_mysql()

    if service_result:
        print("mysql重启成功,正在正常运行")
        save_log("mysql重启成功,正在正常运行")
        sendemail.title = link + "," + "mysql重启成功,正在正常运行"
        sendemail.content = service_log
        sendemail.sendEmail()
        return True
    else:
        print("mysql重启失败")
        save_log("mysql重启失败")
        # sendemail.title = link + "," + "mysql重启失败"
        # sendemail.content = service_log
        # sendemail.sendEmail()
        return False
Exemplo n.º 13
0
def notify(course):
    open('log.txt', 'w').close()
    course_open = 0
    f = open('log.txt', 'r+')
    logtext = ''
    while 1:
        print 'RUNNNING ' + str(course['number'])
        prelog = datetime.datetime.now(
            timezone('US/Central')).strftime("%m/%d %I:%M:%S %p: ")
        if check_open(course):
            if course_open == 0:
                logtext = "{}Opened\n".format(prelog)
                sendEmail("Your class has opened.")
                sleep(5)
                sendEmail(str(course['crn']))
                course_open = 1
        else:
            logtext = "{}Closed\n".format(prelog)
            if course_open == 1:
                sendEmail("Your class has closed")
            course_open = 0
        f.write(logtext)
        f.flush()
        os.fsync(f.fileno())
        sleep(300)
    f.close()
Exemplo n.º 14
0
def process_as3935_interrupt():

    global as3935Interrupt
    global as3935, as3935LastInterrupt, as3935LastDistance, as3935LastStatus

    as3935Interrupt = False

    print "processing Interrupt from as3935"
    # turn I2CBus 0 on
    #tca9545.write_control_register(TCA9545_CONFIG_BUS0)
    # turn I2CBus 2 on
    tca9545.write_control_register(TCA9545_CONFIG_BUS2)
    time.sleep(0.003)
    reason = as3935.get_interrupt()

    as3935LastInterrupt = reason
    
    if reason == 0x00:
	as3935LastStatus = "Spurious Interrupt"
    elif reason == 0x01:
	as3935LastStatus = "Noise Floor too low. Adjusting"
        as3935.raise_noise_floor()
    elif reason == 0x04:
	as3935LastStatus = "Disturber detected - masking"
        as3935.set_mask_disturber(True)
    elif reason == 0x08:
        now = datetime.now().strftime('%H:%M:%S - %Y/%m/%d')
        distance = as3935.get_distance()
	as3935LastDistance = distance
	as3935LastStatus = "Lightning Detected "  + str(distance) + "km away. (%s)" % now
	pclogging.log(pclogging.INFO, __name__, "Lightning Detected "  + str(distance) + "km away. (%s)" % now)
	sendemail.sendEmail("test", "WeatherPi Lightning Detected\n", as3935LastStatus, conf.textnotifyAddress,  conf.textfromAddress, "");
    
    print "Last Interrupt = 0x%x:  %s" % (as3935LastInterrupt, as3935LastStatus)
    tca9545.write_control_register(TCA9545_CONFIG_BUS0)

    time.sleep(0.003)
Exemplo n.º 15
0
def check_website(l):
    try:
        res = requests.get(l, timeout=4)
        url = tldextract.extract(l)
        if res.status_code != 200:
            sendemail.content = "{}.{}发现以下问题:{}".format(
                url.domain, url.suffix, res.text)
            sendemail.title = "{}.{}访问异常了".format(url.domain, url.suffix)

            if not restart_mysql(): reboot_and_wdcp()

        elif res.status_code == 200:
            sendemail.content = "{}.{}目前运行正常:{}".format(
                url.domain, url.suffix,
                html.fromstring(res.content).xpath("//title/text()")[0])
            sendemail.title = "{}.{}目前运行正常".format(url.domain, url.suffix)
            print(sendemail.content)
            save_log(sendemail.content)
            sendemail.sendEmail()
    except Exception as e:
        print("check_website发生异常:{}".format(e))
        save_log("check_website发生异常:{}".format(e))
        time.sleep(10)
        check_website(l)
Exemplo n.º 16
0
def process_as3935_interrupt():
    """Process the AS3935 Interrupt to determine type."""
    global as3935Interrupt
    global as3935, as3935LastInterrupt, as3935LastDistance, as3935LastStatus
    as3935Interrupt = False
    print "processing Interrupt from as3935"
    reason = as3935.get_interrupt()
    as3935LastInterrupt = reason
    if reason == 0x00:
        as3935LastStatus = "Spurious Interrupt"
    if reason == 0x01:
        as3935LastStatus = "Noise Floor too low. Adjusting"
        as3935.raise_noise_floor()
    if reason == 0x04:
        as3935LastStatus = "Disturber detected - masking"
        as3935.set_mask_disturber(True)
    if reason == 0x08:
        now = datetime.now().strftime('%H:%M:%S - %Y/%m/%d')
        distance = as3935.get_distance()
        as3935LastDistance = distance
        as3935LastStatus = "Lightning Detected " + str(distance) + "km away. (%s)" % now
        pclogging.log(pclogging.INFO, __name__, "Lightning Detected " + str(distance) + "km away. (%s)" % now)
        sendemail.sendEmail("test", "WeatherPi Lightning Detected\n", as3935LastStatus, conf.textnotifyAddress,  conf.textfromAddress, "")
    print "Last Interrupt = 0x%x:  %s" % (as3935LastInterrupt, as3935LastStatus)
Exemplo n.º 17
0
    def __init__(self):
	global hs_exit
        self.text = 'Home Security'
        self.pos = [160, 120]
        self.exit = hs_exit;
        
        
        self.temp_flag = config.TempFlag
        self.hum_flag = config.HumFlag
        self.mot_flag = config.MotFlag
        self.run_flag = config.TempFlag or config.HumFlag or config.MotFlag
        
        self.max_temp = config.max_temp
        self.min_temp = config.min_temp
        self.max_humid = config.max_humid
        self.min_humid = config.min_humid
        
        self.ths = temp_detect.temp_hum_sensor(13)
	self.p = pir.pir(19)
    	self.se = sendemail.sendEmail('*****@*****.**')
Exemplo n.º 18
0
def getclassmsg():
    try:
        html1 = urllib.request.urlopen(
            "http://aipt.ucas.ac.cn/index.php/zh-cn/jxgg/5933-3-3-4").read()
        html1 = html1.decode('utf-8')
        part_title = r"<title>(.+?)</title>"
        title = re.compile(part_title).findall(html1)
        # print(title)
        part_table = r"""<table style="width: 707px; height: 302px;">((.|\r\n)+)</table> """
        table = re.compile(part_table).findall(html1)
        html = """<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>%s</title>
    <p><h2>%s</h2></p>
    <table>
""" % (title[0], title[0])
        for x in table:
            for i in x:
                html += i
        html += """
</table>

</body>
</html>
"""
        # 创建sendEmail类
        se = sendemail.sendEmail(html, "*****@*****.**", "html")
        # 格式化发送的表头
        se.set_msg("王晓东", "[%s]sendEmail about UCAS class" % title[0])
        # 进行发送
        se.send()
        # 发送完成退出
        se.close()
        return True
    except Exception as e:
        log.error(e)
        return False
Exemplo n.º 19
0
    log.info('search JOB msg from mysql ---- END ----')
except Exception as e:
    log.error("unable to fetch data")
    log.error(e)

import sendemail

#拼装msg_str
log.info('Assembling msg_str ---- START ----')
msg_str = """"""
msg_str += """***Positionname***\t***Companyname***\t***Workplace***\t***Salary***\t***Posttime***\t***Experience***\n"""
count = 0
for row in results:
    msg_str += """%20s\t%20s\t%10s\t%20s\t%10s\t%10s\n""" % (row[0], row[1], row[2], row[3], row[4], row[5]) # (Positionname, Companyname, Workplace, Salary, Posttime, Experience)
    count += 1
msg_conut = """总计岗位:%d\n""" % count
log.info('Assembling msg_str ---- SUCCESS ----')
# 创建sendEmail类
se = sendemail.sendEmail(
    msg_conut + msg_str,
    config.mail['qq_email_wxd']['email'],
    config.mail['qq_email_wxd']['password'],
    config.sendlist['51job_list']['userlist'].split(','))
# 格式化发送的表头
se.set_msg("王晓东", "[sendEmail]sendEmail V1.0 Test 1st")
# 进行发送
# se.login()
se.send()
# 发送完成退出
se.close()
Exemplo n.º 20
0
        root = ET.fromstring(xml)
    except ET.ParseError:
        print("Class doesn't exist :(")
        return
    avail = root.find('enrollmentStatus').text
    if avail == "Closed" or avail == "UNKNOWN":
        return 0
    else:
        return 1


if __name__ == '__main__':
    while 1:
        print('RUNNNING')
        for course in courses:
            ## book keeping the open status for each course
            if 'open_status' not in course:
                course['open_status'] = False

            if check_open(course['department'], course['number'],
                          course['crn']):
                if course['open_status'] == 0:
                    sendEmail("Your class {}-{} has opened.".format(
                        course['department'], course['number']))
                    course['open_status'] = 1
            else:
                if course['open_status'] == 1:
                    sendEmail("Your class has closed")
                course['open_status'] = 0
        sleep(600)
Exemplo n.º 21
0
    <meta charset="UTF-8">
    <title>table test</title>
</head>
<body>
    <div>
<table border="1">
<tr>
    <td><a href="http://www.w3school.com.cn">This is a link</a></td>
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>
    </div>
</body>
</html>
"""

# 创建sendEmail类
se = sendemail.sendEmail(html, "*****@*****.**", "html")
# 格式化发送的表头
se.set_msg("王晓东", "[sendEmail]sendEmail about html table V1.1 Test 2nd")
# 进行发送
se.send()
# 发送完成退出
se.close()
Exemplo n.º 22
0
                    "SkyWeather2 Startup Version " + config.SWVERSION)

if (config.USEBLYNK):
    updateBlynk.blynkEventUpdate("SW Startup Version " + config.SWVERSION)
    updateBlynk.blynkTerminalUpdate("SW Startup Version " + config.SWVERSION)

subjectText = "The " + config.STATIONKEY + " SkyWeather2 Raspberry Pi has #rebooted."
ipAddress = subprocess.check_output(['hostname', '-I'])
bodyText = "SkyWeather2 Version " + config.SWVERSION + " Startup \n" + ipAddress.decode(
) + "\n"
if (config.SunAirPlus_Present):
    sampleSunAirPlus()
    bodyText = bodyText + "\n" + "BV=%0.2fV/BC=%0.2fmA/SV=%0.2fV/SC=%0.2fmA" % (
        batteryVoltage, batteryCurrent, solarVoltage, solarCurrent)

sendemail.sendEmail("test", bodyText, subjectText, config.notifyAddress,
                    config.fromAddress, "")

if (config.USEBLYNK):
    updateBlynk.blynkInit()

import paho.mqtt.client as mqtt

# set up MQTT
if (config.MQTT_Enable):
    state.mqtt_client = mqtt.Client(client_id="SkyWeather2")
    state.mqtt_client.connect(config.MQTT_Server_URL,
                              port=config.MQTT_Port_Number)

import publishMQTT

# Set up scheduler
Exemplo n.º 23
0
# -*- coding: UTF-8 -*-
# !/usr/bin/python3
# @version: V
# @author: 飞翔的卡夫卡
# @contact: [email protected]
# @site:
# @software: PyCharm
# @file: sendEmail_test.py
# @time: 2018/5/16 15:59
# @python:python3.6

import sendemail

# 创建sendEmail类
se = sendemail.sendEmail('hello World!', '*****@*****.**')
# 格式化发送的表头
se.set_msg("见你就上", "[sendEmail]sendEmail V1.0 Test 1st")
se.send()
# 发送完成退出
se.close()
Exemplo n.º 24
0
def emailSender():
    sendemail.sendEmail(
        user_settings)  #figure out the arguments because settings
Exemplo n.º 25
0
            pclogging.log(pclogging.WARNING, __name__, "WLAN Down, Pi is resetting WLAN connection")
            WLAN_check_flg = WLAN_check_flg + 1  # try to recover
            subprocess.call(['sudo /sbin/ifdown wlan0 && sleep 10 && sudo /sbin/ifup --force wlan0'], shell=True)
        else:
            WLAN_check_flg = 0
            print "WLAN is OK"

print ""
print "WeatherPi Solar Powered Weather Station Version 2.0"
print "Updated by Cameron Rex (camrex) - Original code by SwitchDoc Labs"
print ""
print "Program Started at:" + time.strftime("%Y-%m-%d %H:%M:%S")
print ""

pclogging.log(pclogging.INFO, __name__, "WeatherPi Startup Version 2.0")
sendemail.sendEmail("test", "WeatherPi Startup \n", "The WeatherPi Raspberry Pi has rebooted.", conf.notifyAddress,  conf.fromAddress, "")

secondCount = 1
while True:
    # process Interrupts from Lightning
    if (as3935Interrupt is True):
        try:
            process_as3935_interrupt()
        except:
            print "exception - as3935 I2C did not work"

    # print every 10 seconds
    if ((secondCount % 10) == 0):
        sampleWeather()
        sampleSunAirPlus()
        writeWeatherRecord()
Exemplo n.º 26
0
def executeRemoteCommand(command):
    result = True

    if command == REMOTE_LOCK:
        if hardwareconfig.checkLock() == False:
            AFroutines.lockScreen()
            result = sendemail.sendEmail("Command successful", "Screen locked")
            eventQueue.put(("Log", 'Screen locked due to remote command'))
        else:
            eventQueue.put(
                ("Log", 'Lock screen failed - command received while locked'))
            result = sendemail.sendEmail("Command failed",
                                         "Screen already locked")

    elif command == REMOTE_STARTMONITOR:
        #cant check ispy camera status, just have to assume it was not monitoring
        iSpyPath = fileconfig.config.get('TRIGGERS', 'ispy_path')
        roomCamID = fileconfig.config.get('TRIGGERS', 'room_cam_id')
        if os.path.exists(iSpyPath):
            eventQueue.put(
                ("Log", "Starting room camera due to remote command"))
        else:
            eventQueue.put(
                ("Log",
                 "iSpy executable not found - cannot fulfill remote command"))
            return

        subprocess.call([iSpyPath, 'commands bringonline,2,%s' % roomCamID])
        result = sendemail.sendEmail(
            "Command successful",
            "Movement monitoring initiated. Have a nice day.")

    elif command == REMOTE_STOPMONITOR:
        #cant check ispy camera status, just have to assume it was already monitoring
        iSpyPath = fileconfig.config.get('TRIGGERS', 'ispy_path')
        roomCamID = fileconfig.config.get('TRIGGERS', 'room_cam_id')
        if os.path.exists(iSpyPath):
            eventQueue.put(
                ("Log", "Stopping room camera due to remote command"))
        else:
            eventQueue.put(
                ("Log",
                 "iSpy executable not found - cannot fulfill remote command"))
            return

        subprocess.call([iSpyPath, 'commands takeoffline,2,%s' % roomCamID])
        result = sendemail.sendEmail(
            "Command successful",
            "Movement monitoring disabled. Welcome home!")

    elif command == REMOTE_SHUTDOWN:
        result = sendemail.sendEmail("Command successful", "Shutting down...")
        eventQueue.put(
            ("Log", "Initiating standard shutdown due to remote command"))
        AFroutines.standardShutdown()

    elif command == REMOTE_KILLSWITCH:
        eventQueue.put(
            ("Log", "Initiating emergency shutdown due to remote command"))
        AFroutines.emergency()

    if result != True: eventQueue.put(('Log', 'Mail send failed: %s' % result))
Exemplo n.º 27
0
    all_course = ''
    for course in courses:
        s = course['课程名'] + ' ' + course['学分'] + ' ' + course[
            '课程属性'] + ' ' + course['成绩'] + '\n'
        all_course = all_course + s
    return all_course


if __name__ == "__main__":
    # 登录
    while True:
        f = open("student.json", encoding='utf-8')
        global data
        data = json.load(f)
        print(u'学号: ' + data['zjh'] + '  ' + u'密码: ' + data['mm'])
        if login(True) == 1:
            break

    firsttime = True  # 第一次的话,就选快点,后面有个间隔就好
    initial_courses = grade()
    initial = len(initial_courses)
    sendEmail('初始成绩', normlize(initial_courses))
    while True:
        courses = grade()
        course_sum = len(courses)
        if course_sum > initial:
            # 发送短信
            initial = course_sum
            sendEmail('出成绩了', normlize(courses - initial_courses))
            initial_courses = courses
Exemplo n.º 28
0
    def run(self):
        
        if fileconfig.config.get('TRIGGERS','debuglog') == 'True':
            global VERBOSELOGS
            VERBOSELOGS = True
            
        debugLog('Lockwatcher Started')
        
        global startupTime 
        startupTime = time.time()
        
        #send log/status updates to connections in here - for config programs
        listeners = []
        
        confMonThread = configMonitor()
        confMonThread.start()
        
        LOCKED = fileconfig.config.get('TRIGGERS','lockedtriggers').split(',')
        ALWAYS = fileconfig.config.get('TRIGGERS','alwaystriggers').split(',')
        ACTIVE = LOCKED+ALWAYS
        
        global eventQueue
        eventQueue = Queue.Queue()

        threadStatuses = {}
        threadDict = {}
        
        for trigger in ACTIVE:
            if trigger != '': startMonitor(threadDict,trigger)

        if fileconfig.config.get('EMAIL','ENABLE_REMOTE') == 'True':
            startMonitor(threadDict,'email')
        
        
        #new month, new log
        logPath = fileconfig.config.get('TRIGGERS','logfile')
        if os.path.exists(logPath):
            creationTime = time.ctime(os.path.getctime(logPath))
            creationMonth = datetime.datetime.strptime(creationTime, "%a %b %d %H:%M:%S %Y")
            monthNow = time.strftime('%m %Y')
            if creationMonth != monthNow:
                try:
                    open(logPath, 'w').close()
                except: pass
                    
        eventQueue.put(('Log','Lockwatcher monitoring started'))
        
        badCommands = 0
        shutdownActivated = False
        while True:
            event = eventQueue.get(block=True, timeout=None)
            debugLog('Event in queue: '+str(event))
            eventType = event[0]
            
            #--------------trigger activated under shutdown conditions
            if eventType == 'Kill':
                eventReason = event[1]
                #don't trigger multiple shutdowns but keep logging while we can
                if shutdownActivated == False: 
                    shutdownActivated = True
                    
                    if fileconfig.config.get('EMAIL','email_alert') == 'True' and \
                        'Kill switch' not in eventReason:
                        try:
                            #has a 4 second timeout for blocking operations
                            result = sendemail.sendEmail('Emergency shutdown triggered',eventReason)
                            if result != True:
                                eventQueue.put(('Log','Mail send failed: %s'%result))
                        except:
                            pass #email failed, oh well. 
                    AFroutines.emergency()
            
            #--------------thread status changed, inform any listeners        
            elif eventType == 'Status':
                #if self.statuses != None: self.statuses[event[1]].set(event[2])
                threadStatuses[event[1]] = event[2]
                msg = 'Status::%s::%s'%(event[1],event[2])
                broadcast(listeners,msg)
                
            #-----------config programs can request all the current statuses
            elif eventType == 'getStatuses':
                msg = 'AllStatuses::'
                for name,value in threadStatuses.items():
                    msg = msg+ '%s::%s|'%(name,value)
                msg = msg[:-1]
                
                broadcast(listeners,msg)
            
            #--------------add to log file + listener log window if they exist
            elif eventType == 'Log':
                addLogEntry(str(event[1]),listeners)
                
            elif eventType == 'stop':
                broadcast(listeners,'Shutdown')
                for threadname in threadDict.keys():
                    if isRunning(threadname,threadDict): threadDict[threadname].terminate()
                confMonThread.terminate()
                time.sleep(1) #give threads time to shutdown
                return
            
            elif eventType == 'startMonitor':
                monitor=event[1]
                if monitor in trigMonitorMap.keys():
                    thread = trigMonitorMap[monitor]
                else: continue
                if not isRunning(thread,threadDict): startMonitor(threadDict,trigEventMap[monitor])
            
            elif eventType == 'stopMonitor':
                monitor = event[1]
                
                if monitor == 'devices':
                    threadnames = ['deviceMonitor','volumeMonitor',
                                   'logicalDiskRemoveMonitor','logicalDiskCreateMonitor']
                else:
                    threadnames = [trigMonitorMap[monitor]]
                    
                for threadname in threadnames:
                    if isRunning(threadname,threadDict):
                        threadDict[threadname].terminate()
                        threadDict[threadname] = None
            
            elif eventType == 'Mail':
                #malformed emails would be a good way of crashing lockwatcher
                #be careful to valididate mail here
                validMail = True
                try:
                    command, code = event[1].split(' ')
                    eventQueue.put(('Log','Received mail "%s %s"'%(command,code)))
                except:
                    validMail = False
                    
                #forgive bad command codes - crappy attack and causes
                #loop if we look at our returned emails with same sender/recv addresss
                if validMail == True:
                    try: 
                        command = int(command)
                        if command not in commandList:
                            continue
                    except:
                        continue
                    
                if validMail == True and sendemail.validHMAC(code,command) == True:
                    executeRemoteCommand(command) 
                    badCommands = 0 #good command resets limit
                else:
                    badCommands += 1
                    result = sendemail.sendEmail("Command failed","Bad command or authentication code received: %s"%str(event[1]))
                    if result != True:
                        eventQueue.put(('Log','Mail send failed: %s'%result))
                    eventQueue.put(('Log','Mail not authenticated or bad command: "%s". Ensure clocks are synchronised.'%str(event[1])))
                    badCommandLimit = int(fileconfig.config.get('EMAIL','BAD_COMMAND_LIMIT'))
                    if badCommandLimit > 0 and badCommands >= badCommandLimit:
                        addLogEntry(str(event[1]),listeners)
                        
                        if shutdownActivated == False:
                            shutdownActivated = True
                            AFroutines.emergency()
                            
                    continue
                
            elif eventType == 'reloadConfig':
                fileconfig.reloadConfig()
                if isRunning('keyboardMonitor',threadDict): threadDict['keyboardMonitor'].reloadConfig()
                #eventQueue.put(('Log','Config reload forced'))  #debugmode
                
            elif eventType == 'newListener':
                port = int(event[1])
                s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
                eventQueue.put(('Log','Lockwatcher connected to new configuration client'))
                try:
                    s.connect( ('127.0.0.1', port) )
                except: 
                    eventQueue.put(('Log','Error: Failed to connect to client port: '+str(port)))
                    continue
                
                s.send(b'True@@')
                listeners.append(s)
                
            else:
                eventQueue.put(('Log','Error: Unknown event in queue: '+str(event)))
Exemplo n.º 29
0
    def run(self):

        if fileconfig.config.get('TRIGGERS', 'debuglog') == 'True':
            global VERBOSELOGS
            VERBOSELOGS = True

        debugLog('Lockwatcher Started')

        global startupTime
        startupTime = time.time()

        #send log/status updates to connections in here - for config programs
        listeners = []

        confMonThread = configMonitor()
        confMonThread.start()

        LOCKED = fileconfig.config.get('TRIGGERS', 'lockedtriggers').split(',')
        ALWAYS = fileconfig.config.get('TRIGGERS', 'alwaystriggers').split(',')
        ACTIVE = LOCKED + ALWAYS

        global eventQueue
        eventQueue = Queue.Queue()

        threadStatuses = {}
        threadDict = {}

        for trigger in ACTIVE:
            if trigger != '': startMonitor(threadDict, trigger)

        if fileconfig.config.get('EMAIL', 'ENABLE_REMOTE') == 'True':
            startMonitor(threadDict, 'email')

        #new month, new log
        logPath = fileconfig.config.get('TRIGGERS', 'logfile')
        if os.path.exists(logPath):
            creationTime = time.ctime(os.path.getctime(logPath))
            creationMonth = datetime.datetime.strptime(creationTime,
                                                       "%a %b %d %H:%M:%S %Y")
            monthNow = time.strftime('%m %Y')
            if creationMonth != monthNow:
                try:
                    open(logPath, 'w').close()
                except:
                    pass

        eventQueue.put(('Log', 'Lockwatcher monitoring started'))

        badCommands = 0
        shutdownActivated = False
        while True:
            event = eventQueue.get(block=True, timeout=None)
            debugLog('Event in queue: ' + str(event))
            eventType = event[0]

            #--------------trigger activated under shutdown conditions
            if eventType == 'Kill':
                eventReason = event[1]
                #don't trigger multiple shutdowns but keep logging while we can
                if shutdownActivated == False:
                    shutdownActivated = True

                    if fileconfig.config.get('EMAIL','email_alert') == 'True' and \
                        'Kill switch' not in eventReason:
                        try:
                            #has a 4 second timeout for blocking operations
                            result = sendemail.sendEmail(
                                'Emergency shutdown triggered', eventReason)
                            if result != True:
                                eventQueue.put(
                                    ('Log', 'Mail send failed: %s' % result))
                        except:
                            pass  #email failed, oh well.
                    AFroutines.emergency()

            #--------------thread status changed, inform any listeners
            elif eventType == 'Status':
                #if self.statuses != None: self.statuses[event[1]].set(event[2])
                threadStatuses[event[1]] = event[2]
                msg = 'Status::%s::%s' % (event[1], event[2])
                broadcast(listeners, msg)

            #-----------config programs can request all the current statuses
            elif eventType == 'getStatuses':
                msg = 'AllStatuses::'
                for name, value in threadStatuses.items():
                    msg = msg + '%s::%s|' % (name, value)
                msg = msg[:-1]

                broadcast(listeners, msg)

            #--------------add to log file + listener log window if they exist
            elif eventType == 'Log':
                addLogEntry(str(event[1]), listeners)

            elif eventType == 'stop':
                broadcast(listeners, 'Shutdown')
                for threadname in threadDict.keys():
                    if isRunning(threadname, threadDict):
                        threadDict[threadname].terminate()
                confMonThread.terminate()
                time.sleep(1)  #give threads time to shutdown
                return

            elif eventType == 'startMonitor':
                monitor = event[1]
                if monitor in trigMonitorMap.keys():
                    thread = trigMonitorMap[monitor]
                else:
                    continue
                if not isRunning(thread, threadDict):
                    startMonitor(threadDict, trigEventMap[monitor])

            elif eventType == 'stopMonitor':
                monitor = event[1]

                if monitor == 'devices':
                    threadnames = [
                        'deviceMonitor', 'volumeMonitor',
                        'logicalDiskRemoveMonitor', 'logicalDiskCreateMonitor'
                    ]
                else:
                    threadnames = [trigMonitorMap[monitor]]

                for threadname in threadnames:
                    if isRunning(threadname, threadDict):
                        threadDict[threadname].terminate()
                        threadDict[threadname] = None

            elif eventType == 'Mail':
                #malformed emails would be a good way of crashing lockwatcher
                #be careful to valididate mail here
                validMail = True
                try:
                    command, code = event[1].split(' ')
                    eventQueue.put(
                        ('Log', 'Received mail "%s %s"' % (command, code)))
                except:
                    validMail = False

                #forgive bad command codes - crappy attack and causes
                #loop if we look at our returned emails with same sender/recv addresss
                if validMail == True:
                    try:
                        command = int(command)
                        if command not in commandList:
                            continue
                    except:
                        continue

                if validMail == True and sendemail.validHMAC(code,
                                                             command) == True:
                    executeRemoteCommand(command)
                    badCommands = 0  #good command resets limit
                else:
                    badCommands += 1
                    result = sendemail.sendEmail(
                        "Command failed",
                        "Bad command or authentication code received: %s" %
                        str(event[1]))
                    if result != True:
                        eventQueue.put(
                            ('Log', 'Mail send failed: %s' % result))
                    eventQueue.put((
                        'Log',
                        'Mail not authenticated or bad command: "%s". Ensure clocks are synchronised.'
                        % str(event[1])))
                    badCommandLimit = int(
                        fileconfig.config.get('EMAIL', 'BAD_COMMAND_LIMIT'))
                    if badCommandLimit > 0 and badCommands >= badCommandLimit:
                        addLogEntry(str(event[1]), listeners)

                        if shutdownActivated == False:
                            shutdownActivated = True
                            AFroutines.emergency()

                    continue

            elif eventType == 'reloadConfig':
                fileconfig.reloadConfig()
                if isRunning('keyboardMonitor', threadDict):
                    threadDict['keyboardMonitor'].reloadConfig()
                #eventQueue.put(('Log','Config reload forced'))  #debugmode

            elif eventType == 'newListener':
                port = int(event[1])
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                eventQueue.put(
                    ('Log',
                     'Lockwatcher connected to new configuration client'))
                try:
                    s.connect(('127.0.0.1', port))
                except:
                    eventQueue.put(
                        ('Log', 'Error: Failed to connect to client port: ' +
                         str(port)))
                    continue

                s.send(b'True@@')
                listeners.append(s)

            else:
                eventQueue.put(
                    ('Log', 'Error: Unknown event in queue: ' + str(event)))
Exemplo n.º 30
0
template = env.get_template('serverusage.html')
html_content = template.render(memory_status=memory_status,
                               mem_percent=str(mem_percent),
                               swap_status=swap_status,
                               swap_percent=str(swap_percent),
                               disk_status=disk_status,
                               disk_status_path=disk_status_path,
                               mem_total=round(mem_total),
                               mem_use=round(mem_use),
                               swap_total=round(swap_total),
                               swap_used=round(swap_used),
                               device_used=device_used)

import sendemail
# 创建sendEmail类
se = sendemail.sendEmail(html_content, "*****@*****.**", "html")
# 格式化发送的表头
label = ""
if memory_status == "red" or disk_status == "red" or swap_status == "red":  # 包含19种情况
    label = "Red"
elif (memory_status != "red" and disk_status != "red"
      and swap_status != "red") and (memory_status == "yellow"
                                     or disk_status == "yellow"
                                     or swap_status == "yellow"):  #
    label = "Yellow"
elif memory_status == "green" and disk_status == "green" and swap_status == "green":
    label = "Green"
se.set_msg(
    "东助", "[%s-%s]PI server status is %s !" %
    (label, str(date.today()), label.upper()))
# 登录邮件
Exemplo n.º 31
0
            listings[search] = None

    driver = webdriver.Firefox()
    count = 0
    while(count < 50):

        next_listings = {}
        for search, old_results in listings.items():
            new_results = getListings(driver, search)

            # check for new listings if old results exist
            if old_results != None:
                time.sleep(10)
                for result in new_results:
                    if result not in old_results:
                        count += 1
                        print(result)
                        sendEmail(EMAIL_SUBJECT, result)
            else:
                old_results = []

            if new_results:
                next_listings[search] = new_results
            else: # avoid feeding nothing when getListings incorrectly returns nothing
                next_listings[search] = old_results

        listings = next_listings

        time.sleep(5 * 60)

Exemplo n.º 32
0
                <td>%s MB</td>
                <td bgcolor="%s">%s</td>
            </tr>
    """ % (device, round(device_used[device][0]), round(
        device_used[device][1]), device_used[device][3],
           str(device_used[device][2]) + "%")
msg_str += """
        </table>
    </div>
</body>
</html>
"""

import sendemail
# 创建sendEmail类
se = sendemail.sendEmail(msg_str, "*****@*****.**", "html")
# 格式化发送的表头
label = ""
if memory_status == "red" or disk_status == "red" or swap_status == "red":  # 包含19种情况
    label = "Red"
elif (memory_status != "red" and disk_status != "red"
      and swap_status != "red") and (memory_status == "yellow"
                                     or disk_status == "yellow"
                                     or swap_status == "yellow"):  #
    label = "Yellow"
elif memory_status == "green" and disk_status == "green" and swap_status == "green":
    label = "Green"
se.set_msg(
    "王晓东", "[%s-%s]PI server status is %s !" %
    (label, str(date.today()), label.upper()))
# 登录邮件
Exemplo n.º 33
0
        WLAN_check_flg = 0
        print "WLAN is OK"


print ""
print "WeatherPi Solar Powered Weather Station Version 1.9 - SwitchDoc Labs"
print ""
print ""
print "Program Started at:" + time.strftime("%Y-%m-%d %H:%M:%S")
print ""

DATABASEPASSWORD = "******"
pclogging.log(pclogging.INFO, __name__, "WeatherPi Startup Version 1.9")

sendemail.sendEmail("test", "WeatherPi Startup \n",
                    "The WeatherPi Raspberry Pi has rebooted.",
                    conf.notifyAddress, conf.fromAddress, "")

secondCount = 1
while True:

    # process Interrupts from Lightning

    if (as3935Interrupt == True):

        try:
            process_as3935_interrupt()

        except:
            print "exception - as3935 I2C did not work"
Exemplo n.º 34
0
    if avail == "Closed" or avail == "UNKNOWN":
        return 0
    else:
        return 1

if __name__ == '__main__':
    open('log.txt', 'w').close()
    course_open = 0
    f = open('log.txt', 'r+')
    logtext = ''
    while 1:
        print 'RUNNNING'
        prelog = datetime.datetime.now(timezone('US/Central')).strftime("%m/%d %I:%M:%S %p: ")
        if check_open():
            if course_open == 0:
                logtext = "{}Opened\n".format(prelog)
                sendEmail("Your class has opened.")
                sleep(5)
                sendEmail(str(course['crn']))
                course_open = 1
        else:
            logtext = "{}Closed\n".format(prelog)
            if course_open == 1:
                sendEmail("Your class has closed")
            course_open = 0
        f.write(logtext)
        f.flush()
        os.fsync(f.fileno())
        sleep(1260)
    f.close()
                <td>%s</td>
                <td>%s</td>
                <td>%s</td>
                <td>%s</td>
                <td>%s</td>
                <td>%s</td>
                <td>%s</td>
            </tr>
    """ % (row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7])
    count += 1
msg_str += """
        </table>
    </div>
</body>
</html>
"""

log.info('Assembling msg_str ---- SUCCESS ----')
# 创建sendEmail类
se = sendemail.sendEmail(msg_str, config.mail['qq_email_wxd']['email'],
                         config.mail['qq_email_wxd']['password'],
                         config.sendlist['51job_list']['userlist'].split(','),
                         config.mail['qq_email_wxd']['smtp'], 465, 'html')
# 格式化发送的表头
se.set_msg("王晓东", "[51JOB msg count: %d]sendEmail V1.0 Test 4st" % count)
# 进行发送
# se.login()
se.send()
# 发送完成退出
se.close()
print returnStatusLine("WXLink", config.WXLink_Present)
print
print returnStatusLine("UseMySQL", config.enable_MySQL_Logging)
print returnStatusLine("Check WLAN", config.enable_WLAN_Detection)
print returnStatusLine("WeatherUnderground", config.WeatherUnderground_Present)
print "----------------------"

# initialize appropriate weather variables
currentWindDirection = 0
currentWindDirectionVoltage = 0.0
rain60Minutes = 0.0

pclogging.log(pclogging.INFO, __name__, "GroveWeatherPi Startup Version 2.0")

sendemail.sendEmail("test", "GroveWeatherPi Startup \n",
                    "The GroveWeatherPi Raspberry Pi has #rebooted.",
                    config.notifyAddress, config.fromAddress, "")

if (config.SunAirPlus_Present == False):

    batteryCurrent = 0.0
    batteryVoltage = 4.00
    batteryPower = batteryVoltage * (batteryCurrent / 1000)

    solarCurrent = 0.0
    solarVoltage = 0.0
    solarPower = solarVoltage * (solarCurrent / 1000)

    loadCurrent = 0.0
    loadVoltage = 0.0
    loadPower = loadVoltage * (loadCurrent / 1000)