首页 > 编程语言 >python线性脚本生成基本eml邮件,压缩文件,接口灌数据

python线性脚本生成基本eml邮件,压缩文件,接口灌数据

时间:2023-06-07 17:47:30浏览次数:47  
标签:info name python eml self random 压缩文件 num file

  1 import datetime, zipfile, tarfile, logging, os, string, random, ipaddress, uuid, pytz, py7zr
  2 import io, socket
  3 from email.mime.text import MIMEText
  4 from email.mime.multipart import MIMEMultipart
  5 from email.mime.application import MIMEApplication
  6 from email.utils import formatdate, make_msgid
  7 from email.mime.image import MIMEImage
  8 import email.generator, email.message, threading, multiprocessing, pdb, logging.handlers, linecache
  9 import openpyxl
 10 import tqdm
 11 from faker import Faker
 12 from multiprocessing import Pool
 13 
 14 # email domain dict
 15 email_domain = {
 16     0: 'gmail.com', 1: 'yahoo.com', 2: 'msn.com', 3: 'hotmail.com', 4: 'aol.com', 5: '163.com', 6: 'live.com',
 17     7: 'qq.com', 8: 'ask.com', 9: '0355.com', 10: 'googlemail.com', 11: 'sina.com', 12: 'sougou.com', 13: 'foxmail.com',
 18     14: 'live.com', 15: '163.net', 16: '263.net', 17: 'yeah.net', 18: 'mail.com', 19: 'aim.com', 20: 'walla.com',
 19     21: 'inbox.com', 22: 'hongkong.com', 23: 'ctimail.com', 24: 'hknet.com', 25: 'SEED.NET.TW',
 20     26: 'TOPMARKEPLG.COM.TW', 27: 'PCHOME.COM.TW', 28: 'netzero.net', 29: 'vsnl.com', 30: 'yandex.ru'
 21 }
 22 # link dict
 23 link_dict = {
 24     1: 'https://www.baidu.com',
 25     2: 'https://www.gitee.cn',
 26     3: 'https://www.ccc.net',
 27     4: rf'{random.choice(["www", "https://www"])}.{"".join(random.choices((string.ascii_letters + string.digits + chr(random.randint(0x4E00, 0X9FBF))), k=random.randint(5, 30)))}.{random.choice(["com", "cn", "net"])}',
 28 }
 29 eml_format = {
 30     1: 'eml',
 31     2: 'msg',
 32     3: 'pst',
 33     4: 'fox'
 34 }
 35 type_list = ['rar', 'tgz', 'zip', '7z']
 36 
 37 # txt file path
 38 PATH_TXT = rf'{os.getcwd()}\article_pic'
 39 PATH_SAVE = rf'{os.getcwd()}\eml\eml_file'
 40 PATH_ATTACHMENT = rf'{os.getcwd()}\attachment'
 41 PATH_COMPRESS = rf'{os.getcwd()}\compressfiles'
 42 PATH_LOG = rf'{os.getcwd()}\eml_log'
 43 PATH_MSG = rf'{os.getcwd()}\eml\msg_file'
 44 PATH_TOOL = rf'{os.getcwd()}\tool_msg\MailConverter.exe'
 45 
 46 recip_dict = {}
 47 sender_dict = {}
 48 
 49 
 50 class Domain:
 51 
 52     def __init__(self):
 53         """
 54         define msg structure
 55         """
 56         self.msg = MIMEMultipart()
 57         self.path = ''
 58         logging.basicConfig(level=logging.DEBUG)
 59         handler = logging.handlers.RotatingFileHandler(filename=os.path.join(PATH_LOG, 'eml_log.log'),
 60                                                        maxBytes=20971520, backupCount=20)
 61         self.logger = logging.getLogger()
 62         formatter = logging.Formatter('[%(levelname)s] : [%(asctime)s] : [%(lineno)d]%(message)s')
 63         handler.setFormatter(formatter)
 64         self.logger.setLevel(logging.INFO)
 65         self.logger.addHandler(handler)
 66         self.fake = Faker()
 67 
 68     # read/write file operation
 69     def files_operation(self, name, method, msg_save_flag=False, encoding=None):
 70         """
 71         file read/write operation
 72         :param name: the file name that need operation, full name
 73         :param method: type of operation , read/write
 74         :param msg_save_flag: email save flag
 75         :param encoding: change encoding way , UTF-8 or auto
 76         :return: read return only
 77         """
 78         if 'eml' in name or 'fox' in name or 'msg' in name or 'pst' in name:
 79             self.path = os.path.join(PATH_SAVE, name)
 80         elif 'log' in name:
 81             self.path = os.path.join(PATH_LOG, name)
 82         else:
 83             self.path = os.path.join(PATH_TXT, name)
 84 
 85         if 'rb' in method:
 86             if 'PNG' in name:
 87                 self.path = os.path.join(PATH_TXT, name)
 88             else:
 89                 self.path = os.path.join(PATH_ATTACHMENT, name)
 90 
 91         with open(self.path, method, encoding=encoding) as file:
 92             if 'r' in method:
 93                 if '.log' in name:
 94                     length = len(file.readlines())
 95                     return length
 96                 else:
 97                     print(self.path)
 98                     message = file.read()
 99                     return message
100             elif method == 'w':
101                 if msg_save_flag:
102                     file.write(self.msg.as_string())
103             elif method == 'wb':
104                 if msg_save_flag:
105                     file.write(self.msg.as_bytes())
106                 if 'fox' in name:
107                     gen = email.generator.BytesGenerator(file, mangle_from_=False, maxheaderlen=0)
108                     gen.flatten(self.msg)
109 
110     # create email local
111     def create_emails(self, recip_name, sender_name, create_num, attachment, debug_flag, att_num=1, picture_flag=1, link_flag=1,
112                       flag='close'):
113         """
114 
115         :param recip_name: name list for recipe
116         :param sender_name: name list for sender
117         :param create_num: just for file name
118         :param attachment: whether email need add attachment, 0 true / 1 false
119         :param att_num: attachment number, int
120         :param picture_flag: add picture in eml
121         :param link_flag: add link in article, random location in article or table in the end
122         :param flag: post flag
123         """
124 
125         def cc_list_collect(recip_info):
126             """
127             dispose cc list information
128             :param recip_info:
129             :return:cc_list
130             """
131             choose_cc_set = set(recip_dict.values()) - set(recip_info)
132             return random.sample(list(choose_cc_set), random.randint(1, 10))
133 
134         def add_link(body_of_html):
135             """
136             :param body_of_html:
137             :return: str
138             """
139             # link location in article
140             article_link_flag = random.randint(0, 3)
141             if article_link_flag == 0:
142                 add_num = random.randint(1, 3)
143                 local_random = [random.randint(28, len(body_html) - 7) for _ in range(add_num)]
144                 # link just url not text
145                 for local in local_random:
146                     body_of_html = body_of_html[:int(local)] + f'<a href="{link_dict[random.randint(1, 3)]}">' \
147                                                                f'{link_dict[random.randint(1, 3)]}</a>' + body_of_html[
148                                                                                                           int(local):]
149                 log_info = f'add href in article flag [TRUE], num[{add_num}], url[{link_dict[random.randint(1, 3)]}] '
150             else:
151                 log_info = 'add href in article flag [FALSE]'
152             # link location in the end of article
153             table_flag = random.randint(0, 0)
154             # link in table
155             if table_flag == 0:
156                 body_of_html += '<style>td {height: 50px;width: 200px;text-align: center;vertical-align: middle;} ' \
157                                 'table {margin: auto;}</style>' \
158                                 '<table border="1"><tr><th>index</th><th>link</th><th>end</th></tr>'
159             num_link = random.randint(1, 5)
160             link_choose = [link_dict[random.randint(1, 3)] for _ in range(num_link)]
161             # random num of link
162             for link_add in link_choose:
163                 if table_flag == 0:
164                     body_of_html += f'<tr data_id="{num_link - 1}"><td>click link</td><td><a href="{link_add}">' \
165                                     f'here is a link</a></td><td>jump</td></tr>'
166                 else:
167                     body_of_html += f'<p><a href="{link_add}">here is a href</a></p>'
168             if table_flag == 0:
169                 body_of_html += '</table>'
170                 log_info += 'table flag [TRUE]'
171             if not debug_flag:
172                 self.logger.info(log_info + f' end href num {num_link}, list:{link_choose}')
173             return body_of_html
174 
175         def ip_info_active(num, name, data_real):
176             """
177 
178             :param num: random ip number
179             :param name: recip name
180             :return:list
181             """
182             for _ in range(num):
183                 none_del = []
184                 for ele in [linecache.getline(os.path.join(PATH_LOG, 'ip_info.log'),
185                                               random.randint(1, self.files_operation('ip_info.log', 'r') - 1)
186                                               ).rstrip("\n").split(':') for _ in range(4)]:
187                     if ele != ['']:
188                         none_del.append(ele)
189                 if len(none_del) < 2:
190                     ip_info_active(1, name)
191                 else:
192                     if not debug_flag:
193                         self.logger.info(f'info:{none_del}')
194                     self.msg[
195                         'Received'] = f'from {none_del[0][1]}({random.choice([f"{none_del[0][1]}", "unknown"])} [{none_del[0][0]}]) ' \
196                                       f'by {none_del[1][1]} with {random.choice(["SMTP", "ESMTP"])} ' \
197                                       f'id {uuid.uuid4().hex} for <{name}>; {data_real}'
198                     name = random.choice(list(sender_dict.values()))
199             return num
200 
201         def time_map():
202             start_time = datetime.date(2020, 1, 1)
203             end_time = datetime.date(2020, 12, 31)
204             random_date = start_time + datetime.timedelta(days=random.randint(0, (end_time - start_time).days))
205             start_min = datetime.time(0, 0, 0)
206             end_min = datetime.time(23, 59, 59)
207 
208             random_min = datetime.time(
209                 random.randint(start_min.hour, end_min.hour),
210                 random.randint(start_min.minute, end_min.minute),
211                 random.randint(start_min.second, end_min.second)
212             )
213             random_datetime = datetime.datetime.combine(random_date, random_min)
214             timestamp = random_datetime.timestamp()
215             dt = datetime.datetime.fromtimestamp(timestamp)
216             format_time = dt.strftime('%a, %d %b %Y %H:%M:%S +0800')
217             return format_time
218 
219         # email info
220         save_name = f'2020_{create_num - 1}.{eml_format[random.randint(1, 1)]}'
221         self.msg['Message-ID'] = make_msgid(domain=sender_name.split('@')[-1])
222         eml_data = time_map()
223         # random read ip\domain form file
224         received_num = ip_info_active(random.randint(1, 1), name=sender_name, data_real=eml_data)
225         self.msg['From'] = sender_name
226         self.msg['To'] = ','.join(recip_name)
227         # main email
228         read_message = random.choice([file for file in os.listdir(PATH_TXT) if file.endswith('.txt')])
229         self.msg['Subject'] = read_message.split('.')[0] if not read_message.split('.')[0].isdigit() \
230             else self.fake.sentence(nb_words=10, variable_nb_words=True)
231         info_of_recip = str(recip_name).split('[')[-1].split(']')[0].split(',')
232         body_info = self.files_operation(read_message, 'r', encoding='utf-8')
233         body_html = f'<html><body><div id="info">"{body_info}"</div>'
234 
235         cc_flag = random.randint(0, 2)
236         cc_name = ','.join(cc_list_collect(recip_name))
237         if cc_flag == 0:
238             self.msg['Cc'] = cc_name
239             if not debug_flag:
240                 self.logger.info(f'cc list:{cc_list_collect(recip_name)}')
241 
242         if "p" in flag:
243             self.post_info(sender_name, recip_name, cc_name, attachment, body_info, debug_flag=debug_flag)
244         else:
245             if link_flag == 0:
246                 body_html = add_link(body_html)
247             if picture_flag == 0:
248                 pic_link_flag = random.randint(0, 5)
249                 if pic_link_flag == 0:
250                     # picture only
251                     flag_info = True
252                     body_html += f'<div><p>Here is a img:</p><a href="{link_dict[random.randint(1, 3)]}">' \
253                                  f'<img src="cid:image1"></a></div>'
254                 else:
255                     # picture have a link to jump web
256                     flag_info = False
257                     body_html += f'<div><p>Here is a img:</p><img src="cid:image1"></div>'
258 
259                 picture_add = self.files_operation(
260                     random.choice([file for file in os.listdir(PATH_TXT) if file.endswith('.PNG')]),
261                     'rb')
262                 img = MIMEImage(picture_add)
263                 img.add_header('Content-ID', '<image1>')
264                 self.msg.attach(img)
265                 self.logger.info(f'picture_status:[TRUE]  picture link flag: {flag_info}')
266             else:
267                 self.logger.info('picture_status:[FALSE]')
268             body_html += '</body></html>'
269             body = MIMEText(body_html.encode('utf-8'), 'html', 'utf-8')
270 
271             if 'fox' in save_name:
272                 body.add_header('Content-Disposition', 'inline')
273                 body.add_header('Content-Type', 'text/html; charset=utf-8')
274             self.msg.attach(body)
275 
276             self.logger.info(f'Received number[{received_num}], sender list:{sender_name}')
277             self.logger.info(f'recipe list:{info_of_recip}')
278 
279             # set email time
280             # send_time = formatdate(localtime=True)
281             self.msg['Date'] = eml_data
282             self.logger.info(f'email body from file:{read_message}  '
283                              f' the number of recip:{len(info_of_recip)}  send time:{eml_data}')
284 
285             # add attachment
286             if attachment == 0:
287                 # num = 1  and any other
288                 if att_num == 1:
289                     file_name = [random.choice([file for file in os.listdir(PATH_ATTACHMENT)])]
290                 else:
291                     file_name = random.sample([file for file in os.listdir(PATH_ATTACHMENT)], att_num)
292 
293                 for att_ele in file_name:
294                     att = self.files_operation(att_ele, 'rb')
295                     attachment = MIMEApplication(att, name=att_ele)
296                     attachment['Content-Disposition'] = f'attachment; filename="{att_ele}"'
297                     # attachment.add_header('connect-disposition', 'attachment', filename=att_filename)
298                     self.msg.attach(attachment)
299                 self.logger.info(f"attachment_flag:[TRUE] push attachment num {att_num} Success!")
300                 self.logger.info(f'attachments list:{file_name}')
301             else:
302                 self.logger.info(f"push attachment not this time! attachment_flag:[FALSE]")
303 
304             # save email
305             self.files_operation(save_name, 'wb', msg_save_flag=True)
306             self.logger.info(f'eml file save as {save_name} in {PATH_SAVE}')
307             os.chmod(os.path.join(PATH_SAVE, save_name), 0o600)
308 
309             # random create msg/pst
310             flag_change_type = random.randint(1, 1)
311             if flag_change_type == 0:
312                 os.system(PATH_TOOL + ' ' + 'to-msg' + ' ' + os.path.join(PATH_SAVE, save_name) + ' ' + PATH_MSG)
313                 self.logger.info('change eml -> msg')
314 
315     # IO data to fill the files specify the size
316     def io_size(self, file_name, file_size):
317         """
318         :param file_name: file name which want change size
319         :param file_size: file size you need, 'int' best
320         :return:
321         """
322         while os.path.getsize(file_name) < int(file_size):
323             read_eml_info = self.files_operation(file_name, 'r')
324             eml_size_before = len(read_eml_info)
325             if eml_size_before >= file_size:
326                 break
327             else:
328                 # additional_size = file_size - eml_size_before
329                 # additional_content = ''.join(self.files_operation(
330                 #     random.choice([file for file in os.listdir(PATH_TXT)]), 'r', encoding='utf-8'))
331                 additional_content = ''.join(
332                     self.files_operation(os.path.join(PATH_TXT, '999.txt'), 'r', encoding='utf-8'))
333                 read_eml_info += additional_content
334                 self.files_operation(file_name, 'wb', msg_save_flag=True)
335             # print(len(read_eml_info))
336 
337     @staticmethod
338     def random_name():
339         """
340         random name with string, length 5 - 12
341         :return: str
342         """
343         name_length = random.randint(5, 12)
344         return ''.join(random.choices((string.ascii_letters + string.digits), k=name_length))
345 
346     # compress files
347     def compress_files(self, file_formats, com_time=1, passwd=''):
348         """
349         handles file compression
350         :param file_formats: file format , support .rar/.zip/.msg/.pst/.fox/.7z/tgz
351         :param com_time: the number of times that the file was compressed
352         :param passwd: whether encryption is required, True/False
353         """
354 
355         def file_active(obj, file_name, type_files):
356             """
357             dispose compress files save method
358             :param obj: compress objective
359             :param file_name: filename list
360             :param type_files: compress type
361             """
362             for name in file_name:
363                 if 'tgz' in name or 'zip' in name or 'rar' in name or '7z' in name:
364                     path = os.path.join(PATH_COMPRESS, name)
365                 elif '.eml' in name:
366                     path = os.path.join(PATH_SAVE, name)
367                 elif '.msg' in name:
368                     path = os.path.join(PATH_MSG, name)
369                 else:
370                     path = os.path.join(PATH_ATTACHMENT, name)
371 
372                 if type_files == 'tgz':
373                     obj.add(path, arcname=name)
374                 elif type_files == 'rar' or type_files == '7z':
375                     self.logger.info(f'{path}')
376                     obj.writeall(path, arcname=name)
377                 elif type_files == 'zip':
378                     obj.write(path, arcname=name)
379 
380         for file_format in file_formats:
381             for _ in range(com_time):
382                 file_names = []
383                 # file_list = [file for file in os.listdir(PATH_MSG)] + [file for file in os.listdir(PATH_SAVE)
384                 #                                                      + [file for file in os.listdir(PATH_ATTACHMENT)]]
385                 file_list = [file for file in os.listdir(PATH_SAVE)]
386                 if _ >= 1:
387                     file_names.append([f'test_{_ - 1}.{file_format}'])
388                     file_names[0].append(random.choice(file_list))
389                 else:
390                     # file_names.append(random.sample(file_list, random.randint(1, len(file_list))))
391                     file_names.append(random.sample(file_list, random.randint(1, 10)))
392                 operate = 'w'
393                 if file_format == 'zip':
394                     method = zipfile.ZipFile
395                 elif file_format == 'rar' or file_format == '7z':
396                     method = py7zr.SevenZipFile
397                     # pass
398                 elif file_format == 'tgz':
399                     method = tarfile.open
400                     operate += ':gz'
401                 else:
402                     raise TypeError('file format error!')
403 
404                 with method(os.path.join(PATH_COMPRESS, f'test_{_}.{file_format}'), operate) as active_com:
405                     file_active(active_com, file_names[0], file_format)
406                     if _ < 1:
407                         self.logger.info(f"Success create {file_format} file. File number in doc: {len(file_names[0])}"
408                                          + "\t" + f"File in compress:{file_names[0]}")
409                     # if passwd:
410                     #     active_com.setpassword(passwd)
411 
412     def create_user_sender(self, num):
413         """
414         create user for send and recipe
415         :param num: the number of user you need
416         :return: user dict
417         """
418 
419         def init_name(number, dict_name):
420             for num_user in range(1, int(number / 3)):
421                 name = self.random_name()
422                 full_email = name + '@' + email_domain[random.randint(0, len(email_domain) - 1)]
423                 dict_name[name] = full_email
424 
425         # create user_dict
426         init_name(num, recip_dict)
427         # create sender_dict, half past of user_dict
428         for index, (key, value) in enumerate(recip_dict.items()):
429             if index < len(recip_dict) / 2:
430                 sender_dict[key] = value
431             else:
432                 break
433         init_name(num / 2, sender_dict)
434         self.logger.info(f'number of sender dict: {len(sender_dict)}     number of recipe dict: {len(recip_dict)}')
435 
436     def post_data(self, sender_name, recip_name, cc_name, attachment, body_info):
437         """
438         send json data to ES
439         :param attachment: attachment num
440         :param sender_name: sender list
441         :param recip_name: recip list
442         :param cc_name: cc list
443         :param body_info: html body
444         :return:
445         """
446 
447         import json
448         import hashlib
449 
450         def encrypted_random(num=1):
451             string_enc = "".join(random.choices((string.ascii_letters + string.digits), k=random.randint(0, 10)))
452             if num == 1:
453                 encrypted = hashlib.md5()
454                 encrypted.update(string_enc.encode('utf8'))
455             elif num == 2:
456                 encrypted = hashlib.sha1(string_enc.encode('utf8'))
457             elif num == 3:
458                 encrypted = hashlib.sha256(string_enc.encode('utf8'))
459             else:
460                 raise TypeError('Type error!')
461             return encrypted.hexdigest()
462 
463         def random_num(num):
464             a = 999999999999999999
465             return random.randint(1, int(str(a)[:num]))
466 
467         def str_random(num=22):
468             return "".join(random.choices((string.ascii_letters + string.digits), k=random.randint(0, num)))
469 
470         def choice_list(tp):
471             if tp == 1:
472                 info_list = ["中文"]
473             elif tp == 2:
474                 info_list = ['rar', 'tgz', 'zip', '7z', "pdf_f", "doc_f", "xlsx_f"]
475             else:
476                 raise
477             return random.choice(info_list)
478 
479         def time_map():
480             start_time = datetime.date(2017, 1, 1)
481             end_time = datetime.date(2023, 6, 1)
482             random_date = start_time + datetime.timedelta(days=random.randint(0, (end_time - start_time).days))
483             start_min = datetime.time(0, 0, 0)
484             end_min = datetime.time(23, 59, 59)
485             random_min = datetime.time(
486                 random.randint(start_min.hour, end_min.hour),
487                 random.randint(start_min.minute, end_min.minute),
488                 random.randint(start_min.second, end_min.second)
489             )
490             random_datetime = datetime.datetime.combine(random_date, random_min)
491             timestamp = random_datetime.timestamp()
492             return int(timestamp)
493 
494         random_id = random_num(16)
495         task_id = random_num(16)
496         attachment_id = random_num(16)
497         attachment_md5 = encrypted_random()
498         att_info = attachment_info_num(random.randint(1, 5))
499         url_info = link_dict[random.randint(1, 4)]
500         end_with = random.choice(type_list)
501         eml_domain = email_domain[random.randint(0, 30)]
502 
503         json_info = {}
504 
505         json_data = json.dumps(json_info)
506         return json_data
507 
508     def post_info(self, sender_name, recip_name, cc_name, attachment, body_info, save_xlsx=True, read_from_xlsx=True,
509                   debug_flag=False):
510         import requests
511 
512         def xlsx_file(num_c):
513             excel_work = openpyxl.Workbook()
514             wk_sheet = excel_work.active
515             tqdm_time = 1
516             for _ in range(int(num_c)):
517                 wk_sheet[f'A{_ + 1}'] = str(json_data)
518                 with tqdm.tqdm(total=num_c, desc='progress', unit='num', colour='blue') as pbar:
519                     pbar.update(tqdm_time)
520                     tqdm_time += 1
521             wk_sheet.title = 'json'
522             excel_work.save(os.path.join(r'PATH_SAVE', 'json.xlsx'))
523 
524         def txt_info(num_w, info):
525             for _ in range(num_w):
526                 f = open('E:\data\json.txt', 'w')
527                 f.writelines(info)
528                 f.close()
529 
530         def post_info_active(data_info):
531             for _ in range(10):
532                 res = requests.post('http:url', data=data_info, headers=headers,
533                                     timeout=50)
534                 ela_time = res.elapsed.total_seconds()
535                 print(str(res) + str(ela_time))
536                 if '200' not in str(res):
537                     raise
538 
539         headers = {'Content-Type': 'application/json'}
540         json_data = self.post_data(sender_name, recip_name, cc_name, attachment, body_info)
541 
542         if not read_from_xlsx:
543             post_info_active(json_data)
544         if not save_xlsx:
545             open_time = datetime.datetime.now()
546             workbook = openpyxl.load_workbook(r'D:\pycharm\project\py\xlsx_file\json.xlsx')
547             sheet = workbook.active
548             end_time_read = datetime.datetime.now()
549             line = sheet.max_row
550             print(str(line) + ' ' + str(end_time_read - open_time))
551             for info_json in range(line):
552                 cell = sheet[f'A{info_json + 500000}'].value
553                 print(cell)
554                 post_info_active(cell)
555         else:
556             xlsx_file(1000000)
557             # txt_info(100, str(json_data))
558 
559     # processing logic
560     def generate_process(self, num_eml, debug_create_flag, post_request=False):
561         """
562         main process
563         """
564         logging.info(f'create email number : {num_eml}')
565         # create user/sender dict
566         create_start_time = datetime.datetime.now()
567         self.create_user_sender(500000)
568         print('create user dict SUCCESS!')
569         success_create_dict_time = datetime.datetime.now()
570         if not debug_create_flag:
571             self.logger.info(f'start create user time {create_start_time}, finish time {success_create_dict_time}, '
572                              f'spend {success_create_dict_time - create_start_time}')
573 
574         def create_active(min_trunk_num, max_trunk_num, num_progress, debug_flag):
575             """
576             email create active for threading
577             :return: None
578             """
579             tqdm_time = 1
580             # for trunk_times in range(1, len(num_eml/num_process)+1):
581             while min_trunk_num <= max_trunk_num:
582                 # current progress
583                 if not debug_flag:
584                     with tqdm.tqdm(total=num_progress, desc='progress', unit='num', colour='blue') as pbar:
585                         pbar.update(tqdm_time)
586                         tqdm_time += 1
587                     self.logger.info('-----------------------------------------------')
588                     self.logger.info(f'The current number of cycles : {min_trunk_num}')
589                     # self.logger.info(f'add data in log, exegesis when running')
590                 self.msg = MIMEMultipart()
591                 # random sender
592                 sender_info = sender_dict[random.choice(list(sender_dict.keys()))]
593                 recip_info = [recip_dict[info] for info in
594                               random.choices(list(recip_dict.keys()), k=random.randint(1, 20))]
595                 # reset body if sender = user
596                 if sender_info == recip_info:
597                     min_trunk_num -= 1
598                     continue
599                 min_trunk_num += 1
600                 # create email, random attachment
601                 if not post_request:
602                     post_flag = 'close'
603                 else:
604                     post_flag = 'open'
605                 self.create_emails(recip_info, sender_info, min_trunk_num, attachment=random.randint(0, 0),
606                                    att_num=random.randint(14, 14), picture_flag=random.randint(0, 3),
607                                    link_flag=random.randint(0, 3), debug_flag=debug_flag, flag=post_flag)
608             return None
609 
610         start_time = datetime.datetime.now()
611 
612         create_active(1, num_eml, num_eml, debug_flag=debug_create_flag)
613         end_time = datetime.datetime.now()
614         if not debug_create_flag:
615             self.logger.info(f'process start time {start_time}, '
616                              f'process stop time {end_time}, spend {end_time - start_time}')
617 
618     def mod_choose(self, debug_create_flag=False, is_post=False):
619         """
620         mod choose (delete no effect, just change main objective)
621         :param debug_create_flag: open it that you can debug the demo
622         :param is_post: the way of running, post or save eml
623         """
624         if debug_create_flag:
625             operate_for_user = '0'
626         else:
627             operate_for_user = input(
628                 "choose the sys type(0--create email  1--create compress  2--change file size[coding...]):")
629 
630         if operate_for_user == '0':
631             if debug_create_flag:
632                 num_eml = 1
633             else:
634                 num_eml = int(input("input the number that you want create: "))
635             self.generate_process(num_eml, debug_create_flag=debug_create_flag, post_request=is_post)
636 
637         elif operate_for_user == '1':
638             type_choose = input('choose type(0--all  1--rar 2--tgz 3--zip 4--7z):')
639             com_time = int(input("Warning: compress files must have at least one file!" + "\n"
640                                  + "enter the number of time you want to compress the file (int): "))
641             if type_choose == '0':
642                 type_active = type_list
643             else:
644                 type_active = [type_list[int(type_choose) - 1]]
645             # create compress files after email create
646             compress_start_time = datetime.datetime.now()
647             self.compress_files(type_active, com_time=com_time)
648 
649             compress_complete_time = datetime.datetime.now()
650             self.logger.info(f'compress time {compress_start_time}, complete time {compress_complete_time}, '
651                              f'spend {compress_complete_time - compress_start_time}')
652 
653         elif operate_for_user == '2':
654             file_size = input('input size to change(MB):')
655             self.io_size(os.path.join(PATH_SAVE, random.choice([file for file in os.listdir(PATH_SAVE)])),
656                          int(file_size) * 1024 * 1024)
657 
658 
659 Domain().mod_choose(debug_create_flag=False, is_post=False)

 

标签:info,name,python,eml,self,random,压缩文件,num,file
From: https://www.cnblogs.com/TOvOT/p/17464077.html

相关文章

  • 实验六 turtle绘图与Python库应用编程体验
    试验任务一实验源码 task1fromturtleimport*defmove(x,y):'''画笔移动到坐标(x,y)处'''penup()goto(x,y)pendown()defdraw(n,size=100):'''绘制边长为size的正n变形'''foriinrange(n):......
  • Python: jwt
     importjwtfromdatetimeimportdatetimepayload_data={'sub':'4242','iss':'issuer',#issuerofthetoken'name':'JessicaTemporal','nickname':'Jess&#......
  • Python&Excel办公自动化
    操作工作簿01新建一个excel工作簿#2023-4-17importxlwingsasxw#启动excel,但不新建工作簿app是什么,app是excel程序本身app=xw.App(visible=True,add_book=True)#新建一个工作簿workbook=app.books.add()#保存新建的工作簿workbook.save('D:\python_data/tes......
  • java代码调用Python代码
    1,使用runtime调用Python脚本String[]arguments=newString[]{"E:\\ProgramFiles\\python.exe","E:\\wzCode\\signal.py",Arrays.toString(datas),String.valueOf(Num)};......
  • python基础20
    绝对导入和相对导入绝对导入始终以执行文件位置查找相对导入使用符号(.)句点符(.).表示当前路径..表示上一级目录相对导入就可以不按照执行文件所在位置为基准,而是参照当前文件所在位置当文件中......
  • python的名称空间和作用域
    1、  2、内置名称空间:Python解释器启动则产生,关闭即销毁 全局名称空间:存放的名字:运行顶级代码产生的名字,或者说不是函数的定义,也不是内置的,剩下的都是。存活的周期:Python文件执行则产生,Python文件运行完毕后销毁 局部名称空间:存放的名字:再调用函数时,运行函数体代......
  • 【python练习】排列
    题目给定一个整数n,将数字1∼n排成一排,将会有很多种排列方法。现在,请你按照字典序将所有的排列方法输出。输入格式共一行,包含一个整数n。输出格式按字典序输出所有排列方案,每个方案占一行。代码n=int(input())path=[0foriinrange(n)]used=[Falseforiinrange(n)]de......
  • Python pandas库操作 excel
    Pythonpandas库操作excel特别提示:pandas库是基于numpy库的软件库,因此安装Pandas之前需要先安装numpy库。默认的pandas不能直接读写excel文件,需要安装读、写库即xlrd、xlwt才可以实现xls后缀的excel文件的读写,要想正常读写xlsx后缀的excel文件,还需要安装openpyxl库。数据......
  • 实验六 turtle绘图与python库应用编程体验
    '''task1_1.py'''fromturtleimport*defmove(x,y):penup()goto(x,y)pendown()defdraw(n,size=100):foriinrange(n):fd(size)left(360/n)defmain():pensize(2)pencolor('red&#......
  • 【Python自学】环境搭建
    一、pycharm安装二、python安装打开http://www.python.org(这个是python官网)下载配置环境。点击上方downloads下载对应版本安装后通过【win+r】调出【运行】弹窗,输入“cmd”之后打开【命令提示符】,输入python只要出现“>>>”证明你安装成功了。当你看到“>>>”的时候......