toolkits 0.2.7__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. toolkits/3des/3des.py +93 -0
  2. toolkits/3des/__init__.py +0 -0
  3. toolkits/__init__.py +2 -0
  4. toolkits/basic/__init__.py +0 -0
  5. toolkits/basic/list_helper.py +26 -0
  6. toolkits/config/__init__.py +0 -0
  7. toolkits/config/config_demo.py +43 -0
  8. toolkits/databases/__init__.py +0 -0
  9. toolkits/databases/database_client_util.py +143 -0
  10. toolkits/databases/es_client.py +88 -0
  11. toolkits/databases/hive_client.py +72 -0
  12. toolkits/databases/hive_cmd.py +113 -0
  13. toolkits/databases/hive_helper.py +220 -0
  14. toolkits/databases/redis_mgmt.py +95 -0
  15. toolkits/databases/sql_helper.py +291 -0
  16. toolkits/databases/sqlalchemy_helper.py +71 -0
  17. toolkits/databases/status_check.py +162 -0
  18. toolkits/db_query_demo.py +72 -0
  19. toolkits/libs_core/__init__.py +0 -0
  20. toolkits/libs_core/config_groups_helper.py +60 -0
  21. toolkits/libs_core/config_helper.py +22 -0
  22. toolkits/libs_core/env_prepare.py +145 -0
  23. toolkits/libs_core/load_module.py +46 -0
  24. toolkits/libs_core/mysql_helper.py +151 -0
  25. toolkits/network/__init__.py +0 -0
  26. toolkits/network/ip_helper.py +32 -0
  27. toolkits/network/pdi_helper.py +206 -0
  28. toolkits/network/send_mail.py +105 -0
  29. toolkits/system/__init__.py +0 -0
  30. toolkits/system/aes_cipher.py +44 -0
  31. toolkits/system/basic_utils.py +20 -0
  32. toolkits/system/collections_helper.py +72 -0
  33. toolkits/system/crpyt_helper.py +39 -0
  34. toolkits/system/dict2xml.py +416 -0
  35. toolkits/system/dict_helper.py +29 -0
  36. toolkits/system/excel_helper.py +101 -0
  37. toolkits/system/file_helper.py +52 -0
  38. toolkits/system/load_module.py +47 -0
  39. toolkits/system/priority_tasks.py +199 -0
  40. toolkits/system/process_monitor/__init__.py +0 -0
  41. toolkits/system/process_monitor/process_monitor.py +349 -0
  42. toolkits/system/shell_helper.py +263 -0
  43. toolkits/system/str_helper.py +187 -0
  44. toolkits/system/tasks_deamon/__init__.py +0 -0
  45. toolkits/system/tasks_deamon/tasks_controller.py +70 -0
  46. toolkits/system/tasks_deamon/tasks_multiprocessing.py +134 -0
  47. toolkits/system/tasks_deamon/tasks_process.py +137 -0
  48. toolkits/system/test_shell_helper.py +2 -0
  49. toolkits/system/time_helper.py +175 -0
  50. toolkits/system/win32_env.py +49 -0
  51. toolkits/tookits_app.py +17 -0
  52. toolkits/tookits_cli.py +126 -0
  53. toolkits-0.2.7.dist-info/METADATA +35 -0
  54. toolkits-0.2.7.dist-info/RECORD +56 -0
  55. toolkits-0.2.7.dist-info/WHEEL +4 -0
  56. toolkits-0.2.7.dist-info/entry_points.txt +5 -0
@@ -0,0 +1,32 @@
1
+ import socket
2
+ import struct
3
+
4
+ import sys
5
+ from log4python.Log4python import log
6
+ import importlib
7
+ importlib.reload(sys)
8
+ logger = log("IpHelper")
9
+
10
+
11
+ def map_strip(str):
12
+ tmp = str.lstrip("0")
13
+ if tmp == "":
14
+ tmp = "0"
15
+ return tmp
16
+
17
+
18
+ def ip2long(ipstr):
19
+ split_str = ipstr.split(".")
20
+ split_str_map = list(map(map_strip, split_str))
21
+ ip = ".".join(split_str_map)
22
+ final_ip = 0
23
+ try:
24
+ final_ip = struct.unpack("!I", socket.inet_aton(ip))[0]
25
+ except:
26
+ logger.error("ErrIP: [%s]" % ipstr)
27
+ return final_ip
28
+
29
+
30
+ def long2ip(ip):
31
+ ip = int(ip)
32
+ return socket.inet_ntoa(struct.pack("!I", ip))
@@ -0,0 +1,206 @@
1
+ # -*- coding: utf-8 -*-
2
+ import argparse
3
+ import json
4
+ import pprint
5
+ import sys
6
+ from os.path import dirname, basename
7
+ import xmltodict
8
+ from log4python.Log4python import log
9
+ import traceback
10
+ from unipath import Path
11
+ from xml.dom.minidom import parseString
12
+
13
+ from toolkits.system.dict2xml import dicttoxml
14
+ from toolkits.system.shell_helper import exec_shell_with_pipe
15
+ import importlib
16
+
17
+ importlib.reload(sys)
18
+ logger = log("PdiHelper")
19
+
20
+
21
+ class PdiHelper:
22
+ def __init__(self, pdi_exec):
23
+ self.pdi_exec_path = pdi_exec # "/services/pdi/data-integration/pan.sh"
24
+
25
+ # 定义xml转json的函数
26
+ def xmltojson(self, xmlstr):
27
+ # parse是的xml解析器
28
+ xmlparse = xmltodict.parse(xmlstr)
29
+ # json库dumps()是将dict转化成json格式,loads()是将json转化成dict格式。
30
+ # dumps()方法的ident=1,格式化json
31
+ jsonstr = json.dumps(xmlparse, indent=1)
32
+ return jsonstr
33
+
34
+ # json转xml函数
35
+ def jsontoxml(self, jsonstr):
36
+ # xmltodict库的unparse()json转xml
37
+ xmlstr = xmltodict.unparse(jsonstr)
38
+ return xmlstr
39
+
40
+ def load_xml(self, xml_config_file):
41
+ fp = open(xml_config_file)
42
+ lines = fp.readlines()
43
+ fp.close()
44
+
45
+ config = ""
46
+ for item in lines:
47
+ config += item.strip()
48
+ return config
49
+
50
+ def write_xml(self, new_config_file, config_xml):
51
+ fp_out = open(new_config_file, "w+")
52
+ fp_out.write(config_xml)
53
+ fp_out.close()
54
+
55
+ def covert_xml(self, xml_config_file, config_set):
56
+ str_xml = self.load_xml(xml_config_file)
57
+
58
+ config_json = self.xmltojson(str_xml)
59
+ obj_json = json.loads(config_json)
60
+ print(obj_json)
61
+ my_item_func = lambda x: x
62
+ str_xml = dicttoxml(obj_json, attr_type=False, root=False,
63
+ item_func=my_item_func, expand_list_item_name_flag=False)
64
+
65
+ dom = parseString(str_xml)
66
+ str_xml = dom.toprettyxml()
67
+
68
+ self.write_xml("%s_new" % xml_config_file, str_xml)
69
+
70
+ def covert_config(self, xml_config_file, new_config_file, config_set):
71
+ '''<?xml version="1.0" encoding="utf-8"?>
72
+ <student>
73
+ <course>
74
+ <name>math</name>
75
+ <score>90</score>
76
+ </course><info>
77
+ <name>name</name>
78
+ <sex>male</sex>
79
+ </info>
80
+ <stid>10213</stid>
81
+ <title>1</title>
82
+ <title>2</title>
83
+ <list>
84
+ <hop>
85
+ <a>a</a>
86
+ </hop>
87
+ <hop>
88
+ <a>b</a>
89
+ </hop>
90
+ </list>
91
+ </student>
92
+ # {u'student': {u'info': {u'name': u'name', u'sex': u'male'}, u'course': {u'score': u'90', u'name': u'math'},
93
+ # u'stid': u'10213', u'list': {u'hop': [{u'a': u'a'}, {u'a': u'b'}]}, u'title': [u'1', u'2']}}
94
+ '''
95
+ ret = False
96
+ str_xml = self.load_xml(xml_config_file)
97
+
98
+ config_json = self.xmltojson(str_xml)
99
+ obj_config = json.loads(config_json)
100
+ if self.config_merge(obj_config, config_set):
101
+ my_item_func = lambda x: x
102
+ str_xml = dicttoxml(obj_config, attr_type=False, root=False,
103
+ item_func=my_item_func, expand_list_item_name_flag=False)
104
+ dom = parseString(str_xml)
105
+ str_xml = dom.toprettyxml()
106
+ self.write_xml(new_config_file, str_xml.replace("&quot;", "\""))
107
+ ret = True
108
+ return ret
109
+
110
+ def set_dict(self, dst_dict, key_list, val):
111
+ if len(key_list) > 0:
112
+ key = key_list[0]
113
+ del key_list[0]
114
+ # dst_dict[key] = set_dict_val(dst_dict[key], key_list, val)
115
+
116
+ # logger.debug("Key:[%s]" % key)
117
+ pos_key = key.find("[")
118
+ if pos_key >= 0:
119
+ key_search = key[:pos_key]
120
+ if type(dst_dict) is list:
121
+ key_found = False
122
+ for item in dst_dict:
123
+ if item[key_search] == key[pos_key+1: -1]:
124
+ item = self.set_dict(item, key_list, val)
125
+ key_found = True
126
+ if not key_found:
127
+ logger.debug("Error:key_search[%s] Not Found!!" % key)
128
+ else:
129
+ logger.debug("key_search:[%s]" % key_search)
130
+ raise
131
+ else:
132
+ if key in dict(dst_dict):
133
+ dst_dict[key] = self.set_dict(dst_dict[key], key_list, val)
134
+ else:
135
+ logger.debug("Error:key[%s] not found." % key)
136
+ return dst_dict
137
+ else:
138
+ return val
139
+
140
+ def config_merge(self, config_template, config_list):
141
+ ret = False
142
+ obj_data = None
143
+ try:
144
+ for config_item in config_list:
145
+ key_list = config_item['key'].split(".")
146
+ val_set = config_item['val']
147
+ obj_data = config_template
148
+ config_template = self.set_dict(config_template, key_list, val_set)
149
+ ret = True
150
+ except Exception as ex:
151
+ pprint.pprint(obj_data)
152
+ logger.debug("Ojbect_Data:%s" % pprint.pformat(obj_data))
153
+ logger.debug("Error: %s" % ex)
154
+ logger.debug(traceback.format_exc())
155
+ finally:
156
+ return ret
157
+
158
+ def fetch_data_from_es(self, pdi_config_file, url, query, data_output_path):
159
+ log_path = "%s/log/" % dirname(data_output_path)
160
+ tmp_config_path = "%s/config_tmp/" % dirname(data_output_path)
161
+ log_file_name = "%s/output_%s.log" % (log_path, basename(data_output_path))
162
+ if not Path(log_path).exists():
163
+ Path(log_path).mkdir(True)
164
+
165
+ if not Path(tmp_config_path).exists():
166
+ Path(tmp_config_path).mkdir(True)
167
+
168
+ cmd_ret = False
169
+ try:
170
+ # modify the config
171
+ config_set = [
172
+ {
173
+ 'key': "transformation.step.name[url_query].fields.field.name[url].nullif",
174
+ 'val': url
175
+ },
176
+ {
177
+ 'key': "transformation.step.name[url_query].fields.field.name[req].nullif",
178
+ 'val': query.replace("\n", "")
179
+ },
180
+ {
181
+ 'key': "transformation.step.name[out_put].file.name",
182
+ 'val': data_output_path
183
+ }]
184
+
185
+ final_kettle_config = "%s/%s_new" % (tmp_config_path, basename(pdi_config_file))
186
+ if self.covert_config(pdi_config_file, final_kettle_config, config_set):
187
+ # run process
188
+ cmd = "%s -file %s -logfile %s" % (self.pdi_exec_path, final_kettle_config, log_file_name)
189
+ logger.debug("CMD:[%s]" % cmd)
190
+ exec_shell_with_pipe(cmd)
191
+ cmd_ret = True
192
+ except Exception as ex:
193
+ logger.debug("Error: %s" % ex)
194
+ logger.debug(traceback.format_exc())
195
+ finally:
196
+ return cmd_ret
197
+
198
+ if __name__ == '__main__':
199
+ try:
200
+ parser = argparse.ArgumentParser()
201
+ parser.add_argument("logFile", type=str, help="specify the log file's path")
202
+ args = parser.parse_args()
203
+ print((args.logFile))
204
+ except Exception as ex:
205
+ logger.debug("Error: %s" % ex)
206
+ logger.debug(traceback.format_exc())
@@ -0,0 +1,105 @@
1
+ #!/usr/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ import json
4
+ import sys
5
+ import pprint
6
+ import traceback
7
+ from os.path import basename
8
+ from exchangelib import Configuration, Account, Credentials, DELEGATE, Message, Mailbox, FileAttachment
9
+ from log4python.Log4python import log
10
+ import importlib
11
+
12
+ logger = log("SendMail")
13
+ importlib.reload(sys)
14
+
15
+
16
+ class SendMail:
17
+ def __init__(self, username, password, ews_url, primary_smtp_address):
18
+ self.username = username
19
+ self.password = password
20
+ self.ews_url = ews_url
21
+ self.primary_smtp_address = primary_smtp_address
22
+ self.attach_file_list = []
23
+ self.to_recipients = []
24
+ self.cc_recipients = []
25
+ self.bcc_recipients = []
26
+ self.subject = None
27
+ self.body = None
28
+ self.ews_account = self.connect_mail_server()
29
+
30
+ def connect_mail_server(self):
31
+ credentials = Credentials(username=self.username, password=self.password)
32
+ config = Configuration(service_endpoint=self.ews_url, credentials=credentials)
33
+ account = Account(primary_smtp_address=self.primary_smtp_address, config=config,
34
+ autodiscover=False, access_type=DELEGATE)
35
+ return account
36
+
37
+ @staticmethod
38
+ def read_file_content(file_path):
39
+ fp = open(file_path, "r+")
40
+ lines = fp.readlines()
41
+ return "".join(lines)
42
+
43
+ @staticmethod
44
+ def list_update(list_container, new_data):
45
+ if new_data is not None:
46
+ if type(new_data).__name__ in ["str", "unicode"]:
47
+ list_container.append(new_data)
48
+ else:
49
+ list_container.extend(new_data)
50
+ return list_container
51
+
52
+ def mail_receiver(self, to_recipients, cc_recipients=None, bcc_recipients=None):
53
+ self.list_update(self.to_recipients, to_recipients)
54
+ self.list_update(self.cc_recipients, cc_recipients)
55
+ self.list_update(self.bcc_recipients, bcc_recipients)
56
+
57
+ def mail_assemble(self, subject, body, attach_file_list=None):
58
+ self.list_update(self.attach_file_list, attach_file_list)
59
+ logger.debug("attach_files:%s" % json.dumps(self.attach_file_list))
60
+ self.subject = subject
61
+ self.body = body
62
+
63
+ def mail_send(self, receive_mailer, subject, mail_body, attach_file=None):
64
+ if self.to_recipients is None:
65
+ return False
66
+
67
+ self.mail_receiver(receive_mailer)
68
+ if attach_file:
69
+ self.mail_assemble(subject, mail_body, attach_file)
70
+ else:
71
+ self.mail_assemble(subject, mail_body)
72
+
73
+ m = Message(
74
+ account=self.ews_account,
75
+ subject=self.subject,
76
+ body=self.body,
77
+ to_recipients=list(set(self.to_recipients)),
78
+ cc_recipients=list(set(self.cc_recipients)),
79
+ bcc_recipients=list(set(self.bcc_recipients))
80
+ )
81
+
82
+ for item in self.attach_file_list:
83
+ logger.debug("attach_file:%s" % str(item))
84
+ m.attach(FileAttachment(name=basename(item), content=self.read_file_content(item)))
85
+ m.send()
86
+ return True
87
+
88
+
89
+ if __name__ == '__main__':
90
+ try:
91
+ username = "lijiayue"
92
+ password = "please change to your mail info"
93
+ ews_url = "https://mail.qq.com/EWS/Exchange.asmx"
94
+ receive_mail = "lijiayue@qq.com"
95
+ primary_smtp_address = "lijiayue@qq.com"
96
+
97
+ csv_file = "%s/%s" % ("/var/log/", "访问.csv")
98
+ csv_detail_file = "/var/log/test.txt"
99
+
100
+ mail = SendMail(username, password, ews_url, primary_smtp_address)
101
+ mail.mail_send(receive_mail, "发现违规访问用户", "\n日期:%s; 人员数量:%s;\n访问,见附件:%s\n详细访问信息,见附件:%s\n\n",
102
+ [csv_file, csv_detail_file])
103
+ except Exception as ex:
104
+ pprint.pprint("Error: %s" % ex)
105
+ pprint.pprint(traceback.format_exc())
File without changes
@@ -0,0 +1,44 @@
1
+ import base64
2
+ from Crypto.Cipher import AES
3
+ from Crypto import Random
4
+
5
+
6
+ BS = 16
7
+ pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
8
+ unpad = lambda s: s[:-ord(s[len(s)-1:])]
9
+
10
+
11
+ class AESCipher:
12
+ def __init__(self, key, iv_code=None):
13
+ self.key = key
14
+ self.iv_random_flag = False
15
+
16
+ if iv_code:
17
+ self.iv = iv_code
18
+ else:
19
+ self.iv_random_flag = True
20
+ self.iv = Random.new().read(AES.block_size)
21
+
22
+ def encrypt(self, raw):
23
+ raw = pad(raw)
24
+ cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
25
+
26
+ if self.iv_random_flag:
27
+ ret = base64.b64encode(self.iv + cipher.encrypt(raw))
28
+ else:
29
+ ret = base64.b64encode(cipher)
30
+ return ret
31
+
32
+ def decrypt(self, enc):
33
+ enc = base64.b64decode(enc)
34
+
35
+ if self.iv_random_flag:
36
+ self.iv = enc[:16]
37
+
38
+ cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
39
+
40
+ if self.iv_random_flag:
41
+ ret = unpad(cipher.decrypt(enc[16:]))
42
+ else:
43
+ ret = unpad(cipher.decrypt(enc))
44
+ return ret
@@ -0,0 +1,20 @@
1
+ import os
2
+ import sys
3
+
4
+
5
+ def add_relative_search_path(relative_path_list):
6
+ caller_file_path = sys._getframe(1).f_code.co_filename
7
+ path_base = os.path.dirname(os.path.realpath(caller_file_path))
8
+
9
+ for item in relative_path_list:
10
+ path_final = "%s/%s" % (path_base, item)
11
+ sys.path.append(path_final)
12
+
13
+
14
+ def get_script_directory():
15
+ caller_file_path = sys._getframe(1).f_code.co_filename
16
+ return os.path.dirname(os.path.realpath(caller_file_path))
17
+
18
+
19
+ def get_working_directory():
20
+ return os.getcwd()
@@ -0,0 +1,72 @@
1
+ # -*- coding: utf-8 -*-
2
+ from functools import reduce
3
+ from collections import Iterator
4
+ from itertools import chain,groupby,product
5
+
6
+
7
+ class CollectionsHelper:
8
+ def __init__(self, src=None):
9
+ self.src=src
10
+
11
+ def toList(self):
12
+ return list(self.src)
13
+
14
+ def toSet(self):
15
+ return set(self.src)
16
+
17
+ def toTuple(self):
18
+ return tuple(self.src)
19
+
20
+ def getSource(self):
21
+ return self.src
22
+
23
+ def map(self,func):
24
+ return CollectionsHelper(list(map(func, self.src)))
25
+
26
+ def filter(self,predicate):
27
+ return CollectionsHelper(list(filter(predicate, self.src)))
28
+
29
+ def reduce(self,func,identity=None):
30
+ if identity is None:
31
+ return reduce(func,self.src)
32
+ else:
33
+ return reduce(func,self.src,identity)
34
+
35
+ def chain(self):
36
+ return CollectionsHelper(chain.from_iterable(self.src))
37
+
38
+ def groupby(self,func=None):
39
+ return CollectionsHelper([(it[0], list(it[1])) for it in groupby(self.src, func)])
40
+
41
+ def product(self,tag):
42
+ return CollectionsHelper(product(self.src, tag))
43
+
44
+ def all(self,predicate):
45
+ return all([predicate(it) for it in self.src])
46
+
47
+ def any(self,predicate):
48
+ return any([predicate(it) for it in self.src])
49
+
50
+ def first(self,predicate=None):
51
+ if predicate is None:
52
+ if isinstance(self.src,Iterator):
53
+ return next(self.src)
54
+ return next(iter(self.src))
55
+ else :
56
+ return next(list(filter(predicate,self.src)))
57
+
58
+ def firstOrNone(self,predicate=None):
59
+ try:
60
+ if predicate is None:
61
+ if isinstance(self.src,Iterator):
62
+ return next(self.src)
63
+ return next(iter(self.src))
64
+ else :
65
+ return next(list(filter(predicate,self.src)))
66
+ except StopIteration:
67
+ return None
68
+
69
+
70
+ if __name__ == '__main__':
71
+ testgroupdata=[{"id":1,"name":"wwb"},{"id":1,"name":"wxa"},{"id":1,"name":"wxb"},{"id":2,"name":"wxc"},{"id":2,"name":"wxd"}]
72
+ print((CollectionsHelper(testgroupdata).groupby(lambda it:it['id']).toList()))
@@ -0,0 +1,39 @@
1
+ # -*- coding: utf-8 -*-
2
+ import argparse
3
+ import sys
4
+ from log4python.Log4python import log
5
+ from simplecrypt import encrypt, decrypt
6
+ import traceback
7
+ from unipath import Path
8
+ import importlib
9
+
10
+ importlib.reload(sys)
11
+ logger = log("MisUserActionEtl")
12
+
13
+
14
+ def encrypt_file(file_name):
15
+ ciphertext = encrypt('password', plaintext)
16
+
17
+
18
+ def decrypt_file(file_name):
19
+ if not Path(file_name).exists():
20
+ pass
21
+ plaintext = decrypt('password', ciphertext)
22
+
23
+ if __name__ == '__main__':
24
+ try:
25
+ parser = argparse.ArgumentParser()
26
+ parser.add_argument("action", type=str, help="action: [encrypt|decrypt]")
27
+ parser.add_argument("file_path", type=str, help="action: [encrypt|decrypt]")
28
+ args = parser.parse_args()
29
+
30
+ if args.action not in ['encrypt', 'decrypt']:
31
+ print("action value was wrong! please check.[encrypt|decrypt]")
32
+
33
+ if args.action == 'encrypt':
34
+ encrypt_file(args.file_path)
35
+ elif args.action == 'decrypt':
36
+ decrypt_file(args.file_path)
37
+ except Exception as ex:
38
+ logger.debug("Error: %s" % ex)
39
+ logger.debug(traceback.format_exc())