Пример #1
0
def main():
    for dbname, dbhost_map in db_map.items():
        masterNode = dbhost_map.get('master')
        slaveNode = dbhost_map.get('slave')
        masterName = masterNode[0]
        masterPort = masterNode[1]
        slaveName = slaveNode[0]
        slavePort = slaveNode[1]
        masterHostItems = host_map.get(masterName)
        masterHostIp = masterHostItems[1]
        slaveHostItems = host_map.get(slaveName)
        slaveHostIp = slaveHostItems[1]

        msg = '%s %s 监测%s: master:%s:%s:%d \n slave:%s:%s:%d\n' % (today(), now(), dbname,
            masterName, masterHostIp, masterPort, slaveName, slaveHostIp, slavePort)

        #判断主服务同步连接数
        if not isSync(masterHostIp, masterPort, slaveHostIp, slavePort):
            restartSync(slaveHostIp, slavePort, dbname)
            if not isSync(masterHostIp, masterPort, slaveHostIp, slavePort):
                sendmail('告警:数据库同步异常', msg)
                log.error('告警:数据库同步异常:[%s]' % msg)

        #判断从服务同步连接数
        if not isSync(slaveHostIp, slavePort, masterHostIp, masterPort):
            restartSync(masterHostIp, masterPort, dbname)
            if not isSync(slaveHostIp, slavePort, masterHostIp, masterPort):
                sendmail('告警:数据库同步异常', msg)
                log.error('告警:数据库同步异常:[%s]' % msg)
Пример #2
0
Файл: nd.py Проект: stedolan/nd
 def reset_password(self):
     if not self.has_account():
         raise Exception("User account is disabled, password cannot be reset")
     pw = generate_password()
     self.passwd(pw)
     addr = self.get_attribute("mail")
     if addr is None:
         lwarn("No mail address recorded for user %s (%s), can't send password reset message" % 
               (self.get_attribute("uid"), self.get_attribute("cn")))
     else:
         sendmail("password_reset", to=addr, username=self.uid, password=pw)
Пример #3
0
    def send_new_account_email(self):
        '''Sends either the "You've Renewed, Netsoc Still Works" email, or the
        "Please Finish Signing Up and Get And Account" email.

        Requires that the user is a current member, see mark_member.

        Users who already have shell accounts are assumed to be renewing'''
        assert current_session() in self.tcdnetsoc_membership_year
        st = self.get_state()
        assert st in ["newmember","shell"]
        if st == "newmember":
            # create a url and send it to them
            url = accountrequests.make_signup_url(self)
            print "Sending account_creation email for %r to %s" % (self,self.mail)
            sendmail("account_creation", to=self.mail, url=url)
        else:
            # just send an email
            print "Sending account_renewed email for %r to %s" % (self,self.mail)
            sendmail("account_renewed", to=self.mail, username=self.uid)
Пример #4
0
def get_once_media_by_api():
    global next_bid
    json_data = search_by_inm(searchQuery,
                              '201101010000',
                              '201201010000',
                              next=next_bid)
    for tweet in json_data['results']:
        print(tweet)
    exit()
    global max_id
    # help(api.search)
    # return
    new_tweets = api.search(q=searchQuery, count=100, max_id=max_id)
    for tweet in new_tweets:
        item = {}
        item['tweepy_id'] = tweet.id_str
        item['text'] = tweet.text
        item['create_at'] = tweet.created_at
        if sinceId in str(tweet.created_at):
            sendmail("*****@*****.**")
            exit()
        item['user_id'] = tweet.user.id_str
        item['retweet_count'] = tweet.retweet_count
        item['favorite_count'] = tweet.favorite_count
        try:
            item['retweeted_id'] = tweet.retweeted_status.id_str
            item['retweeted'] = 1
        except:
            item['retweeted'] = 0
        item['hashtags'] = ''
        for tag in tweet.entities['hashtags']:
            item['hashtags'] = item['hashtags'] + '#' + tag['text']
        if is_exists(item['tweepy_id']):
            log('已经存在item:', item)
            continue
        log('插入item:', item)
        global_db.insert('tweepy', item)
        if item['retweet_count'] > 0:
            get_this_rt(item['tweepy_id'])
        max_id = item['tweepy_id']
Пример #5
0
def main():
    cache = redis.StrictRedis('127.0.0.1', 6379)

    cmdpath = '/home/maintainer/monitor'
    cmd = '"%s/basecmd.sh up_h"' % (cmdpath)

    host_list = host_map.keys()
    host_list.sort()
    for name in host_list:
        host_set = host_map.get(name)
        key = 'restart|%s' % (name)
        if cache.exists(key):
            up_time = cache.get(key)
        else:
            up_time = '0'

        ip1 = host_set[1]
        
        (returncode, out_lines) = sshIpCmd(ip1, cmd)
        if returncode == 0:
            value_list = out_lines[0].split('|')

            curr_up_time = value_list[0]
            display_up_time = value_list[1]
            #判断启动时间是否相差60秒
            if abs(int(up_time) - int(curr_up_time)) > 30:
                #提示,并邮件通知
                msg = '服务器%s:%s被重启,重启时间:%s,原启动时间:%s, 影响数据库:%s' % (
                    name, ip1, display_up_time, up_time, 
                    '与'.join(getDbFormHost(name)))
                sendmail('告警:服务器异常重启', msg)
                # print msg
                cache.set(key, curr_up_time)
        else:
            print "命令执行出错 %d " % (returncode)
            print out_lines
Пример #6
0
def signup():
    username = request.form['username']
    password = request.form['password']
    email = request.form['email']
    print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    print(username + '\n' + password + '\n' + email)
    if (mydao.is_registed(int(username)) != False):
        return '<script>alert("该用户已注册,请不要重复注册!");window.location.href="/"</script>'
    else:
        result = get_class(username, password, email)
        if (result == 1):
            title = '注册成功'
            text = '恭喜你已成功注册课表/成绩推送小助手\n\n开学时课表推送功能会自动开启,每天向你推送明天要上的课以及天气\n\n成绩推送功能会在考试周每当你有新成绩出来时向你推送成绩\n\n若要停用某功能,仅需在邮件中回复"退订课表"或者"退订成绩"即可'
            mail_result = sendmail(email, text, title, username)
            if (mail_result == 1):
                f = open('registed.txt', 'a+')
                f.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') +
                        ':' + username + '注册成功!\n')
                f.close()
                print(username + "注册成功!")
                return '<script>alert("注册成功,已发送一封邮件到你的邮箱,若未收到请检查邮箱是否填写错误");window.location.href="/"</script>'
            else:
                f = open('registed.txt', 'a+')
                f.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') +
                        ':' + username + '注册邮件发送失败!\n')
                f.close()
                print(username + "邮箱填写错误!")
                result = '<script>alert("注册失败,请检查邮箱是否填写错误!\n"' + email + ');window.location.href="/"</script>'
                return result
        else:
            f = open('registed.txt', 'a+')
            f.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') +
                    ':' + username + '注册失败!\n')
            f.close()
            print(username + result)
            result = '<script>alert("' + result + '");window.location.href="/"</script>'
            return result
Пример #7
0
tm = tm2 = 0;
lm = lm2 = 0;
thenRows = 0
logcount = 0
logcount2 = 0
while True:
    tnow = datetime.datetime.now().time()
    offlinetime = datetime.time(22, 0, 0, 0)
    onlinetime = datetime.time(4, 0, 0, 0)
    # put time on comnplication 3
    timecomp()
    while tnow > offlinetime or tnow < onlinetime:  # checks for offline from file inserted through cron
        timecomp()
        if logcount2 == 0:
            logging.debug(str(datetime.datetime.now()) + " offline")
            sendmail("offline", 0, 0, NSN, 5)
            print str(datetime.datetime.now()) + " offline"
            circles(1, red); circles(2, red); circles(3, red)
            footers(1); footers(2); footers(3)
            number(1, "offline"); number(2, "offline"); number(3, "offline")
            complications(1); complications(2)
            comptext(1, c1t); comptext(2, c2t)
            compnumber(1, "offline"); compnumber(2, "offline")
            logcount2 = 1

        # EXIT#
        for event in pygame.event.get():
            if event.type == pygame.QUIT or event.type == KEYDOWN:
                pygame.quit()
                sys.exit()
        lcd.blit(background, (0, 0))
Пример #8
0
def get_scores(username, password, email, sname, total_scores_count,
               uncomment_scores):
    while (True):
        resp = do_login(username, password)
        soup = BeautifulSoup(resp.text, 'html.parser')
        if (soup.title.string.replace(
                '\n', '').strip() == '三峡大学教务管理系统'):  # 提取title的值并剔除其中的换行符和字符串
            print('登录成功!')
            score_resp = session.get(score_url)  #跳转到分数表页面
            score_soup = BeautifulSoup(score_resp.text, 'html.parser')
            session.get(logout_url)  #退出登录
            print('退出成功!')
            sname = soup.body.find('span', {
                'id': 'ctl00_lblSignIn'
            }).string  #爬取姓名
            sname = re.sub(r'([\d]+)', '', sname)
            print(sname)
            trList = score_soup.body.find(
                id="ctl00_MainContentPlaceHolder_GridScore").findAll('tr')
            flag = 0
            newscore_count = 0
            new_scores = ""
            for tr in trList[1:]:
                tdList = tr.findAll("td")
                score_year = tdList[0].get_text()
                score_term = tdList[1].get_text()
                coursename = tdList[2].get_text()
                credit = tdList[3].get_text()
                test_type = tdList[4].get_text()
                grade = tdList[5].get_text()
                coursenum = tdList[7].get_text()
                if (int(score_year) == year
                        and int(score_term) == term):  #筛选出当前学期
                    if (dao.mydao.is_the_new_score(int(username), coursename,
                                                   year, term)):  #判断最新成绩
                        dao.mydao.insert_score(int(username),
                                               year, term, coursename,
                                               float(credit), test_type, grade)
                        flag = 1
                        newscore_count = newscore_count + 1
                        new_scores = new_scores + coursename + " " + credit + " " + test_type + " " + grade + " " + str(
                            calgpa(grade)) + "\n"
                    else:
                        for uncomment_score in uncomment_scores:
                            if (int(username) == uncomment_score['stu_id']
                                    and coursename
                                    == uncomment_score['coursename']):
                                dao.mydao.update_score(int(username),
                                                       coursename, year, term,
                                                       grade)
            if (flag):  #如果有新成绩出来
                all_scores = ""
                scores = dao.mydao.select_score(int(username), year,
                                                term)  #查询数据库中所有成绩
                current_scores_count = len(scores)
                for score in scores:
                    all_scores = all_scores + score['coursename'] + " " + str(
                        score['credit']) + " " + score[
                            'test_type'] + " " + score['grade'] + " " + str(
                                score['gpa']) + "\n"
                text = "滴滴滴,亲爱的" + sname + "同学,你今天有" + str(
                    newscore_count
                ) + "门新成绩出来啦!\n课程名称  学分  考试类型  成绩  绩点\n" + new_scores + "\n"
                if (current_scores_count == total_scores_count):  #所有成绩都出来了
                    text = text + "你总共有" + str(
                        total_scores_count
                    ) + "门课,到目前为止所有成绩均已出来,分别是:\n课程名称  学分  考试类型  成绩  绩点\n" + all_scores
                    dao.mydao.shutdown_score(int(username))  #关闭成绩推送
                else:
                    text = text + "你总共有" + str(
                        total_scores_count) + "门课,到目前为止已有" + str(
                            current_scores_count
                        ) + "门成绩出来啦!分别是:\n" + all_scores
                title = "滴滴滴,出新成绩啦!"
                if (sname == "朱海晴"):
                    sname = "晴姐"
                result = sendmail(email, text, title, sname)  #发送邮件
                if result:
                    print("邮件发送成功")
                else:
                    print("邮件发送失败")
            break
        else:  #登录失败
            error = soup.find_all('span')[0].get_text()  #提取错误信息
            if (error == '登录失败: 请检查用户名和密码是否输入正确'):
                return error
            elif (error == '登录失败: 该用户已经登录系统,不允许重复登录!'):
                return error
            elif (error == '登录失败: ' + username + '不合法'):  #这三种错误无法进入系统,所以退出循环
                return error
            else:
                print(error)  #验证码不对  继续循环
Пример #9
0
        total_scores_count = user['course_count']
        print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        print(user['stu_id'], user['password'], user['email'], user['sname'])
        print('发送邮件的前一步')
        get_scores(str(user['stu_id']), user['password'], user['email'],
                   user['sname'], total_scores_count, uncomment_scores)
        current_score_count = len(
            mydao.select_score(user['stu_id'], year, term))
        print('总课程:%d' % total_scores_count, '当前课程:%d' % current_score_count)
        if (total_scores_count == current_score_count):
            mydao.shutdown_score(user['stu_id'])
        print('发送邮件的后一步')
    return usercount


if __name__ == '__main__':
    a = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    starttime = time.time()
    usercount = sendscore()
    endtime = time.time()
    costtime = endtime - starttime
    print('开始时间:', a)
    print('结束时间:', time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
    print('用户数量:%d' % usercount, ',耗费总时间(秒):%0.2f' % costtime,
          ',平均耗时(秒):%0.2f' % (float(costtime / usercount)))
    text = "开始时间:" + a + "\n结束时间:" + time.strftime(
        "%Y-%m-%d %H:%M:%S", time.localtime()) + "\n用户数量:" + str(
            usercount) + "\n耗费总时间:%0.2f" % costtime + "\n平均耗时:%0.2f" % float(
                costtime / usercount)
    sendmail('*****@*****.**', text, '已发送', '汪俊')
Пример #10
0
#!/usr/bin/env python

from datetime import datetime
import settings
import logging
from sendmail import *


store = settings.NSN

logging.basicConfig(filename = 'debug.log', level = logging.DEBUG)

logging.debug(str(datetime.now()) + " rebooting")
sendmail("rebooting",0,0,store,5)
Пример #11
0
from random import *
from time import *
from sendmail import *
import RPi.GPIO as GPIO
button_pin = 7
led_pin = 5
GPIO.setmode(GPIO.BOARD)
GPIO.setup(led_pin, GPIO.OUT)
GPIO.setup(button_pin, GPIO.IN)
GPIO.setwarnings(False)

while True:
	if(GPIO.input(button_pin)==False):
		print("THE BUTTON WORKS LEL")
		GPIO.output(led_pin, True);
		sleep(0.4)
		sendmail()
		GPIO.output(led_pin, False);
		
Пример #12
0
# mail timers for not spamming notifications initialized for first pass
tm = tm2 = datetime(1999, 1, 1, 0, 0, 0, 0)
lm = lm2 = datetime(1999, 1, 1, 0, 0, 0, 0)
onlineFirstRun = True
offlineFirstRun = True
fromOffline = False

while True:  # Main Loop contains 1 loop for offline and 1 loop for online

    while datetime.now().time() > offlinetime or datetime.now().time() < onlinetime:
        timecomp()
        if offlineFirstRun:
            logging.debug(str(timenow()) + '  offline')
            try:
                sendmail("offline", 0, 0, NSN, 5)
            except socket.gaierror:
                logging.debug(str(timenow()) + ' email failed')
            except SMTPRecipientsRefused:
                logging.debug(str(timenow()) + ' email failed SMTPRecipientsRefused')
            print str(datetime.now()) + " offline"
            for i in range(1, 4):
                circles(i, red)
                travelList(i)
                number(i, "offline")
                complications(i)
                comptext(i, ct[i - 1])
                compnumber(i, "offline")
            offlineFirstRun = False

        lcd.blit(background, (0, 0))
Пример #13
0
tm = tm2 = datetime.datetime(1999,1,1,0,0,0,0)
lm = lm2 = datetime.datetime(1999,1,1,0,0,0,0)
thenRows = 0
logcount = 0
logcount2 = 0

while True:
    offlinetime = datetime.time(22, 0, 0, 0)
    onlinetime = datetime.time(4, 0, 0, 0)
    timecomp()

    while datetime.datetime.now().time() > offlinetime or datetime.datetime.now().time() < onlinetime:
        timecomp()
        if logcount2 == 0:
            logging.debug(str(datetime.datetime.now()) + " offline")
            sendmail("offline", 0, 0, NSN, 5)
            print str(datetime.datetime.now()) + " offline"
            circles(1, red); circles(2, red); circles(3, red)
            footers(1); footers(2); footers(3)
            number(1, "offline"); number(2, "offline"); number(3, "offline")
            complications(1); complications(2)
            comptext(1, c1t); comptext(2, c2t)
            compnumber(1, "offline"); compnumber(2, "offline")
            logcount2 = 1

        # EXIT#
        for event in pygame.event.get():
            if event.type == pygame.QUIT or event.type == KEYDOWN:
                pygame.quit()
                sys.exit()
        lcd.blit(background, (0, 0))
Пример #14
0
import sys
from settings import *
import datetime
from sendmail import *
import os
import logging
import socket

logging.basicConfig(filename='logs/debug2.log', level=logging.DEBUG)

logging.debug(str(datetime.datetime.now()) + ' Running Check started')

# PID for TPD is logged in pid.txt, checks if running and restarts if not
with open('logs/pid.txt', 'r') as qq:
    qqq = qq.readline()
pidpath = "/proc/" + str(qqq)

now = datetime.datetime.now()
msg = str(now) + ' TPD not updating restarting now'
msg2 = str(now) + ' TPD is working'

if os.path.exists(pidpath) is False:
    try:
        sendmail(msg, 0, 0, NSN, 5)
    except socket.gaierror:
        logging.debug(str(now) + ' email failed')
    logging.debug(msg)
    os.system("sudo shutdown -r now")
else:
    logging.debug(msg2)
Пример #15
0
Файл: nd.py Проект: stedolan/nd
 def sendmail(self, msg, **kw):
     ''' Email the given message to this User '''
     sendmail(msg, {"To": '"%s" <%s>' % (self.cn, self.mail)}, **kw)
Пример #16
0
from random import *
from time import *
from sendmail import *
import RPi.GPIO as GPIO
button_pin = 7
led_pin = 5
GPIO.setmode(GPIO.BOARD)
GPIO.setup(led_pin, GPIO.OUT)
GPIO.setup(button_pin, GPIO.IN)
GPIO.setwarnings(False)

while True:
    if (GPIO.input(button_pin) == False):
        print("THE BUTTON WORKS LEL")
        GPIO.output(led_pin, True)
        sleep(0.4)
        sendmail()
        GPIO.output(led_pin, False)
Пример #17
0
#!/usr/bin/env python

from datetime import datetime
import settings
import logging
from sendmail import *

store = settings.NSN

logging.basicConfig(filename='debug.log', level=logging.DEBUG)

logging.debug(str(datetime.now()) + " rebooting")
sendmail("rebooting", 0, 0, store, 5)
Пример #18
0
Файл: nd.py Проект: stedolan/nd
 def sendmail(self, msg, **kw):
     sendmail(msg, {"To": '"%s" <%s>' % (self.cn, self.mail)}, **kw)
Пример #19
0
tm = tm2 = 0
lm = lm2 = 0
thenRows = 0
logcount = 0
logcount2 = 0
while True:
    tnow = datetime.datetime.now().time()
    offlinetime = datetime.time(22, 0, 0, 0)
    onlinetime = datetime.time(4, 0, 0, 0)
    # put time on comnplication 3
    timecomp()
    while tnow > offlinetime or tnow < onlinetime:  # checks for offline from file inserted through cron
        timecomp()
        if logcount2 == 0:
            logging.debug(str(datetime.datetime.now()) + " offline")
            sendmail("offline", 0, 0, NSN, 5)
            print str(datetime.datetime.now()) + " offline"
            circles(1, red)
            circles(2, red)
            circles(3, red)
            footers(1)
            footers(2)
            footers(3)
            number(1, "offline")
            number(2, "offline")
            number(3, "offline")
            complications(1)
            complications(2)
            comptext(1, c1t)
            comptext(2, c2t)
            compnumber(1, "offline")
Пример #20
0
def main2():

    basecmd = 'netstat -an | grep ESTABLISHED | egrep'

    for dbname, dbhost_map in db_map.items():
        masterNode = dbhost_map.get('master')
        slaveNode = dbhost_map.get('slave')
        masterName = masterNode[0]
        masterPort = masterNode[1]
        slaveName = slaveNode[0]
        slavePort = slaveNode[1]
        masterHostItems = host_map.get(masterName)
        masterHostIp = masterHostItems[1]
        slaveHostItems = host_map.get(slaveName)
        slaveHostIp = slaveHostItems[1]

        msg = '%s %s 监测%s: master:%s:%s:%d \n slave:%s:%s:%d\n' % (today(), now(), dbname,
            masterName, masterHostIp, masterPort, slaveName, slaveHostIp, slavePort)

        filter_ip = '%s:%s.*%s:|%s:.*%s:%s' % (
            masterHostIp, masterPort, slaveHostIp,
            masterHostIp, slaveHostIp, slavePort)

        sshcmd = "%s '%s'" % (basecmd, filter_ip)
        (returncode, master_out_lines) = sshIpCmd(masterHostIp, sshcmd)
        masterConnectCount = len(master_out_lines)

        status = True
        if masterConnectCount < 2:
            msg += '根据服务器:%s的连接数分析,数据同步出问题,需要服务器:%s重启同步\n' % (
                masterHostIp, slaveHostIp)
            msg += '命令:%s 输入如下:\n' % sshcmd
            msg += '\n'.join(master_out_lines)

            cmd = 'ssh root@%s "/home/maintainer/monitor/basecmd.sh resync %d"' % (slaveHostIp, slavePort)
            (returncode, out_lines) = execute_command(cmd)
            log.info('已重启%s服务器%d端口%s库的同步服务' % (slaveHostIp, slavePort, dbname))
            status = False

        filter_ip = '%s:%s.*%s:|%s:.*%s:%s' % (
            slaveHostIp, slavePort, masterHostIp,
            slaveHostIp, masterHostIp, masterPort)

        sshcmd = "%s '%s'" % (basecmd, filter_ip)
        (returncode, slave_out_lines) = sshIpCmd(slaveHostIp, sshcmd)
        slaveConnectCount = len(slave_out_lines)

        if slaveConnectCount < 2:
            msg += '根据服务器:%s的连接数分析,数据同步出问题,需要服务器:%s重启同步\n' % (
                slaveHostIp, masterHostIp)
            msg += '命令:%s 输入如下:\n' % sshcmd
            msg += '\n'.join(slave_out_lines)

            cmd = 'ssh root@%s "/home/maintainer/monitor/basecmd.sh resync %d"' % (masterHostIp, masterPort)
            (returncode, out_lines) = execute_command(cmd)
            log.info('已重启%s服务器%d端口%s库的同步服务' % (masterHostIp, masterPort, dbname))

            status = False
        if not status:
            if dbname != "dd8989":
                sendmail('告警:数据库同步异常', msg)
            log.error('告警:数据库同步异常 [%s]' % msg)
Пример #21
0
lm = lm2 = datetime.datetime(1999, 1, 1, 0, 0, 0, 0)
thenRows = 0
logcount = 0
logcount2 = 0

while True:
    offlinetime = datetime.time(22, 0, 0, 0)
    onlinetime = datetime.time(4, 0, 0, 0)
    timecomp()

    while datetime.datetime.now().time(
    ) > offlinetime or datetime.datetime.now().time() < onlinetime:
        timecomp()
        if logcount2 == 0:
            logging.debug(str(datetime.datetime.now()) + " offline")
            sendmail("offline", 0, 0, NSN, 5)
            print str(datetime.datetime.now()) + " offline"
            circles(1, red)
            circles(2, red)
            circles(3, red)
            footers(1)
            footers(2)
            footers(3)
            number(1, "offline")
            number(2, "offline")
            number(3, "offline")
            complications(1)
            complications(2)
            comptext(1, c1t)
            comptext(2, c2t)
            compnumber(1, "offline")