toolkits 0.2.6__tar.gz → 0.2.8__tar.gz

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 (69) hide show
  1. toolkits-0.2.8/PKG-INFO +35 -0
  2. toolkits-0.2.8/README.md +17 -0
  3. toolkits-0.2.8/pyproject.toml +35 -0
  4. toolkits-0.2.8/src/toolkits/3des/3des.py +93 -0
  5. toolkits-0.2.8/src/toolkits/config_parser/config_demo.py +43 -0
  6. toolkits-0.2.8/src/toolkits/config_parser/config_groups_helper.py +60 -0
  7. toolkits-0.2.8/src/toolkits/config_parser/config_helper.py +22 -0
  8. toolkits-0.2.8/src/toolkits/config_parser/env_prepare.py +145 -0
  9. toolkits-0.2.8/src/toolkits/databases/mysql_helper.py +151 -0
  10. toolkits-0.2.8/src/toolkits/db_query_demo.py +71 -0
  11. toolkits-0.2.8/src/toolkits/libs_core/load_module.py +46 -0
  12. toolkits-0.2.8/src/toolkits/system/__init__.py +0 -0
  13. toolkits-0.2.8/src/toolkits/system/process_monitor/__init__.py +0 -0
  14. {toolkits-0.2.6 → toolkits-0.2.8/src}/toolkits/system/shell_helper.py +62 -6
  15. toolkits-0.2.8/src/toolkits/system/tasks_deamon/__init__.py +0 -0
  16. toolkits-0.2.8/src/toolkits/system/test_shell_helper.py +2 -0
  17. toolkits-0.2.8/src/toolkits/tookits_app.py +17 -0
  18. toolkits-0.2.8/src/toolkits/tookits_cli.py +125 -0
  19. toolkits-0.2.8/tests/__init__.py +0 -0
  20. toolkits-0.2.8/tests/test_shell_helper.py +6 -0
  21. toolkits-0.2.8/tests/test_tookits.py +19 -0
  22. toolkits-0.2.6/MANIFEST.in +0 -4
  23. toolkits-0.2.6/PKG-INFO +0 -23
  24. toolkits-0.2.6/README.rst +0 -4
  25. toolkits-0.2.6/setup.cfg +0 -4
  26. toolkits-0.2.6/setup.py +0 -45
  27. toolkits-0.2.6/toolkits.egg-info/PKG-INFO +0 -23
  28. toolkits-0.2.6/toolkits.egg-info/SOURCES.txt +0 -47
  29. toolkits-0.2.6/toolkits.egg-info/dependency_links.txt +0 -1
  30. toolkits-0.2.6/toolkits.egg-info/not-zip-safe +0 -1
  31. toolkits-0.2.6/toolkits.egg-info/requires.txt +0 -6
  32. toolkits-0.2.6/toolkits.egg-info/top_level.txt +0 -1
  33. {toolkits-0.2.6/toolkits/basic → toolkits-0.2.8/src/toolkits/3des}/__init__.py +0 -0
  34. {toolkits-0.2.6 → toolkits-0.2.8/src}/toolkits/__init__.py +0 -0
  35. {toolkits-0.2.6/toolkits/databases → toolkits-0.2.8/src/toolkits/basic}/__init__.py +0 -0
  36. {toolkits-0.2.6 → toolkits-0.2.8/src}/toolkits/basic/list_helper.py +0 -0
  37. {toolkits-0.2.6/toolkits/network → toolkits-0.2.8/src/toolkits/config_parser}/__init__.py +0 -0
  38. {toolkits-0.2.6/toolkits/system → toolkits-0.2.8/src/toolkits/databases}/__init__.py +0 -0
  39. {toolkits-0.2.6 → toolkits-0.2.8/src}/toolkits/databases/database_client_util.py +0 -0
  40. {toolkits-0.2.6 → toolkits-0.2.8/src}/toolkits/databases/es_client.py +0 -0
  41. {toolkits-0.2.6 → toolkits-0.2.8/src}/toolkits/databases/hive_client.py +0 -0
  42. {toolkits-0.2.6 → toolkits-0.2.8/src}/toolkits/databases/hive_cmd.py +0 -0
  43. {toolkits-0.2.6 → toolkits-0.2.8/src}/toolkits/databases/hive_helper.py +0 -0
  44. {toolkits-0.2.6 → toolkits-0.2.8/src}/toolkits/databases/redis_mgmt.py +0 -0
  45. {toolkits-0.2.6 → toolkits-0.2.8/src}/toolkits/databases/sql_helper.py +0 -0
  46. {toolkits-0.2.6 → toolkits-0.2.8/src}/toolkits/databases/sqlalchemy_helper.py +0 -0
  47. {toolkits-0.2.6 → toolkits-0.2.8/src}/toolkits/databases/status_check.py +0 -0
  48. {toolkits-0.2.6/toolkits/system/process_monitor → toolkits-0.2.8/src/toolkits/libs_core}/__init__.py +0 -0
  49. {toolkits-0.2.6/toolkits/system/tasks_deamon → toolkits-0.2.8/src/toolkits/network}/__init__.py +0 -0
  50. {toolkits-0.2.6 → toolkits-0.2.8/src}/toolkits/network/ip_helper.py +0 -0
  51. {toolkits-0.2.6 → toolkits-0.2.8/src}/toolkits/network/pdi_helper.py +0 -0
  52. {toolkits-0.2.6 → toolkits-0.2.8/src}/toolkits/network/send_mail.py +0 -0
  53. {toolkits-0.2.6 → toolkits-0.2.8/src}/toolkits/system/aes_cipher.py +0 -0
  54. {toolkits-0.2.6 → toolkits-0.2.8/src}/toolkits/system/basic_utils.py +0 -0
  55. {toolkits-0.2.6 → toolkits-0.2.8/src}/toolkits/system/collections_helper.py +0 -0
  56. {toolkits-0.2.6 → toolkits-0.2.8/src}/toolkits/system/crpyt_helper.py +0 -0
  57. {toolkits-0.2.6 → toolkits-0.2.8/src}/toolkits/system/dict2xml.py +0 -0
  58. {toolkits-0.2.6 → toolkits-0.2.8/src}/toolkits/system/dict_helper.py +0 -0
  59. {toolkits-0.2.6 → toolkits-0.2.8/src}/toolkits/system/excel_helper.py +0 -0
  60. {toolkits-0.2.6 → toolkits-0.2.8/src}/toolkits/system/file_helper.py +0 -0
  61. {toolkits-0.2.6 → toolkits-0.2.8/src}/toolkits/system/load_module.py +0 -0
  62. {toolkits-0.2.6 → toolkits-0.2.8/src}/toolkits/system/priority_tasks.py +0 -0
  63. {toolkits-0.2.6 → toolkits-0.2.8/src}/toolkits/system/process_monitor/process_monitor.py +0 -0
  64. {toolkits-0.2.6 → toolkits-0.2.8/src}/toolkits/system/str_helper.py +0 -0
  65. {toolkits-0.2.6 → toolkits-0.2.8/src}/toolkits/system/tasks_deamon/tasks_controller.py +0 -0
  66. {toolkits-0.2.6 → toolkits-0.2.8/src}/toolkits/system/tasks_deamon/tasks_multiprocessing.py +0 -0
  67. {toolkits-0.2.6 → toolkits-0.2.8/src}/toolkits/system/tasks_deamon/tasks_process.py +0 -0
  68. {toolkits-0.2.6 → toolkits-0.2.8/src}/toolkits/system/time_helper.py +0 -0
  69. {toolkits-0.2.6 → toolkits-0.2.8/src}/toolkits/system/win32_env.py +0 -0
@@ -0,0 +1,35 @@
1
+ Metadata-Version: 2.1
2
+ Name: toolkits
3
+ Version: 0.2.8
4
+ Summary: toolkits for quickly reference
5
+ Author-Email: li_jia_yue <59727816@qq.com>
6
+ License: MIT
7
+ Requires-Python: >=3.9
8
+ Requires-Dist: fire>=0.6.0
9
+ Requires-Dist: arrow>=1.3.0
10
+ Requires-Dist: pytest>=8.2.2
11
+ Requires-Dist: icecream>=2.1.3
12
+ Requires-Dist: schedule>=1.2.2
13
+ Requires-Dist: jmespath>=1.0.1
14
+ Requires-Dist: unicodecsv>=0.14.1
15
+ Requires-Dist: log4python>=1.0.11
16
+ Requires-Dist: unipath>=1.1
17
+ Description-Content-Type: text/markdown
18
+
19
+ # toolkits
20
+ ## 迁移PDM项目
21
+ 1, Create virtual env
22
+ pdm venv create
23
+
24
+ 2, Install dependency
25
+ pdm install
26
+
27
+ 3, basic python libs
28
+ pdm add arrow toolkits requests dingtalkchatbot exchangelib redis PyYAML sqlalchemy kafka-python-ng urllib3==1.26.15 wheel jmespath log4python PyMySQL pytest crython icecream
29
+
30
+ ## 使用包中的Python脚本
31
+ ### 设置Python环境变量
32
+ export PYTHONPATH="/home/pythonDemo/toolkits/src/:$PYTHONPATH"
33
+ ### 源码目录中不要有[与包名一致的Python脚本文件]
34
+ ### 直接调用Python脚本
35
+ python toolkits/db_query_demo.py --config_path="/home/pythonDemo/toolkits/src/toolkits/config/config_demo.py" worker test_01.txt
@@ -0,0 +1,17 @@
1
+ # toolkits
2
+ ## 迁移PDM项目
3
+ 1, Create virtual env
4
+ pdm venv create
5
+
6
+ 2, Install dependency
7
+ pdm install
8
+
9
+ 3, basic python libs
10
+ pdm add arrow toolkits requests dingtalkchatbot exchangelib redis PyYAML sqlalchemy kafka-python-ng urllib3==1.26.15 wheel jmespath log4python PyMySQL pytest crython icecream
11
+
12
+ ## 使用包中的Python脚本
13
+ ### 设置Python环境变量
14
+ export PYTHONPATH="/home/pythonDemo/toolkits/src/:$PYTHONPATH"
15
+ ### 源码目录中不要有[与包名一致的Python脚本文件]
16
+ ### 直接调用Python脚本
17
+ python toolkits/db_query_demo.py --config_path="/home/pythonDemo/toolkits/src/toolkits/config/config_demo.py" worker test_01.txt
@@ -0,0 +1,35 @@
1
+ [project]
2
+ name = "toolkits"
3
+ version = "0.2.8"
4
+ description = "toolkits for quickly reference"
5
+ authors = [
6
+ { name = "li_jia_yue", email = "59727816@qq.com" },
7
+ ]
8
+ dependencies = [
9
+ "fire>=0.6.0",
10
+ "arrow>=1.3.0",
11
+ "pytest>=8.2.2",
12
+ "icecream>=2.1.3",
13
+ "schedule>=1.2.2",
14
+ "jmespath>=1.0.1",
15
+ "unicodecsv>=0.14.1",
16
+ "log4python>=1.0.11",
17
+ "unipath>=1.1",
18
+ ]
19
+ requires-python = ">=3.9"
20
+ readme = "README.md"
21
+
22
+ [project.license]
23
+ text = "MIT"
24
+
25
+ [project.scripts]
26
+ toolkits = "toolkits.toolkits_cli:main"
27
+
28
+ [build-system]
29
+ requires = [
30
+ "pdm-backend",
31
+ ]
32
+ build-backend = "pdm.backend"
33
+
34
+ [tool.pdm]
35
+ distribution = true
@@ -0,0 +1,93 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import pyDes
4
+ import base64
5
+
6
+
7
+ class TripleDesUtils:
8
+ des_mode = {"CBC": pyDes.CBC, "ECB": pyDes.ECB}
9
+ des_pad_mode = {"PAD_PKCS5": pyDes.PAD_PKCS5, "PAD_NORMAL": pyDes.PAD_NORMAL}
10
+
11
+ def __init__(self, mode, pad_mode, key, iv, pad=None, trans_base64=False):
12
+ """
13
+ :param mode: des 加密模式,目前支持 CBC,ECB
14
+ :param pad_mode: 目前支持 PAD_PKCS5,PAD_NORMAL
15
+ :param trans_base64: 加密结果是否以 base64 格式输出
16
+ :param key: 密钥
17
+ :param iv: 偏移量
18
+ :param pad:
19
+ """
20
+ self.trans_base64 = trans_base64
21
+ self.k = pyDes.triple_des(key, TripleDesUtils.des_mode.get(mode), iv, pad, TripleDesUtils.des_pad_mode.get(pad_mode))
22
+
23
+ def encryption(self, data):
24
+ """
25
+ 3des 加密
26
+ 说明: 3DES数据块长度为64位,所以IV长度需要为8个字符(ECB模式不用IV),密钥长度为16或24个字符(8个字符以内则结果与DES相同
27
+ IV与密钥超过长度则截取,不足则在末尾填充'\0'补足
28
+ :param data: 待加密数据
29
+ :return:
30
+ """
31
+ _encryption_result = self.k.encrypt(data)
32
+ if self.trans_base64:
33
+ _encryption_result = self._base64encode(_encryption_result)
34
+ return _encryption_result
35
+
36
+ def decrypt(self, data):
37
+ """
38
+ 3des 解密
39
+ :param data: 待解密数据
40
+ :return:
41
+ """
42
+ if self.trans_base64:
43
+ data = self._base64decode(data)
44
+ _decrypt_result = self.k.decrypt(data)
45
+ return _decrypt_result
46
+
47
+ @staticmethod
48
+ def _base64encode(data):
49
+ """
50
+ base 64 encode
51
+ :param data: encode data
52
+ :return:
53
+ """
54
+ try:
55
+ _b64encode_result = base64.b64encode(data)
56
+ except Exception as e:
57
+ raise Exception("base64 encode error:{e}")
58
+ return _b64encode_result
59
+
60
+ @staticmethod
61
+ def _base64decode(data):
62
+ """
63
+ base 64 decode
64
+ :param data: decode data
65
+ :return:
66
+ """
67
+ try:
68
+ _b64decode_result = base64.b64decode(data)
69
+ except Exception as e:
70
+ raise Exception("base64 decode error:{e}")
71
+ return _b64decode_result
72
+
73
+
74
+ if __name__ == "__main__":
75
+ test_data = "12345678a"
76
+ key_a = "uusafeuusafeuusafeuusafe"
77
+ key_b = "jiayufeuusafeuusafeuusaf"
78
+ # [12345678a] 3des Result: 2yjtt0Y/c7xEOa9VGetBVA==
79
+ DesObj = TripleDesUtils(mode="CBC", pad_mode="PAD_PKCS5", key=key_a, iv="01234567", trans_base64=True)
80
+ result_a = DesObj.encryption(test_data)
81
+ print("加密结果: %s" % result_a)
82
+ DesObj = TripleDesUtils(mode="CBC", pad_mode="PAD_PKCS5", key=key_b, iv="01234567", trans_base64=True)
83
+ result_b = DesObj.encryption(result_a)
84
+ print("加密结果: %s" % result_b)
85
+
86
+ # result2 = DesObj.decrypt(result)
87
+ # print("解密结果: %s" % result2)
88
+ DesObj = TripleDesUtils(mode="CBC", pad_mode="PAD_PKCS5", key=key_b, iv="01234567", trans_base64=True)
89
+ result_a = DesObj.encryption(test_data)
90
+ print("加密结果: %s" % result_a)
91
+ DesObj = TripleDesUtils(mode="CBC", pad_mode="PAD_PKCS5", key=key_a, iv="01234567", trans_base64=True)
92
+ result_b = DesObj.encryption(result_a)
93
+ print("加密结果: %s" % result_b)
@@ -0,0 +1,43 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ config_global = {
4
+ "db_list": {
5
+ 'dev_ops': {
6
+ 'desc': "Home 数据库",
7
+ 'db_name': "dev_ops",
8
+ 'user_name': 'root',
9
+ 'password': '4tKTiDYr81YM',
10
+ 'host': "192.168.100.155",
11
+ 'port': 6606
12
+ },
13
+ 'online_alarm': {
14
+ 'desc': "16.15 数据库",
15
+ 'user_name': 'db_admin',
16
+ 'password': '123QWEas!@#',
17
+ 'host': "10.83.16.15",
18
+ 'port': 8012,
19
+ 'db_name': "sec_admin"
20
+ }
21
+ },
22
+ "kafka_list": {
23
+ "home": {
24
+ 'host': "192.168.100.155",
25
+ 'port': 9092
26
+ }
27
+ },
28
+ "redis_list": {
29
+ "home": {
30
+ 'password': 's1hKcWqRj9Se',
31
+ 'host': '192.168.100.155',
32
+ 'port': 9379,
33
+ 'db': 1
34
+ }
35
+ },
36
+ "zookeeper_list": {
37
+ "home": {
38
+ "bin_path": "/usr/local/dev/kafka/kafka_2.12-2.3.0",
39
+ "ip": "192.168.100.155",
40
+ "port": "2184"
41
+ }
42
+ }
43
+ }
@@ -0,0 +1,60 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+
4
+ class ConfigGroupsHelper:
5
+ """
6
+ ConfigGroupsHelper
7
+ """
8
+ def __init__(self, config_groups, config_groups_type="list"):
9
+ self.__group_config = {}
10
+ if config_groups_type == "list":
11
+ self.__init_config_list(config_groups)
12
+ elif config_groups_type == "dict":
13
+ self.__init_config_dict(config_groups)
14
+
15
+ def __init_config_dict(self, config_groups_dict, talk_groups=None):
16
+ init_groups = {}
17
+ chat_groups = dict(config_groups_dict)
18
+ if talk_groups:
19
+ if type(talk_groups) is dict:
20
+ chat_groups = {
21
+ "default": talk_groups
22
+ }
23
+
24
+ if chat_groups:
25
+ for item in chat_groups.keys():
26
+ init_groups[item] = chat_groups[item]
27
+
28
+ self.__group_config = init_groups
29
+
30
+ def __init_config_list(self, config_groups, talk_groups=None):
31
+ init_groups = {}
32
+ chat_groups = config_groups
33
+ if talk_groups:
34
+ if type(talk_groups) is dict:
35
+ chat_groups = [talk_groups]
36
+ else:
37
+ chat_groups = talk_groups
38
+
39
+ if chat_groups:
40
+ for item in chat_groups:
41
+ init_groups[item['name']] = item
42
+
43
+ self.__group_config = init_groups
44
+
45
+ def get_config_by_name(self, config_name):
46
+ config = None
47
+ if config_name not in self.__group_config.keys():
48
+ err_msg = "配置名称不存在,请检查!!"
49
+ print(err_msg)
50
+ exit(1)
51
+ else:
52
+ config = self.__group_config[config_name]
53
+ return config
54
+
55
+ def list_config_groups(self, config_name=""):
56
+ groups = self.__group_config.keys()
57
+ print("%s-配置组:\n" % config_name)
58
+ for item_group in groups:
59
+ desc = self.__group_config[item_group]['desc']
60
+ print("\tName: %s\tDesc:[%s]" % (item_group, desc))
@@ -0,0 +1,22 @@
1
+ # -*- coding: utf-8 -*-
2
+ from toolkits.libs_core.load_module import LoadModule
3
+
4
+
5
+ class ConfigHelpers:
6
+ def __init__(self):
7
+ pass
8
+
9
+ @staticmethod
10
+ def load_config(config_file):
11
+ app = LoadModule()
12
+ config_info = app.load_from_file(config_file)
13
+ return config_info
14
+
15
+ @staticmethod
16
+ def get_config_by_name(config_data, config_name):
17
+ config_info = None
18
+ if config_data:
19
+ config_info = config_data.__dict__[config_name]
20
+
21
+ return config_info
22
+
@@ -0,0 +1,145 @@
1
+ # -*- coding: utf-8 -*-
2
+ import os
3
+ import platform
4
+ import sys
5
+ import traceback
6
+
7
+ import fire
8
+ import jmespath
9
+ from log4python.Log4python import log
10
+ from toolkits.system.basic_utils import get_script_directory
11
+ from toolkits.system.shell_helper import exec_shell
12
+ from unipath import Path
13
+
14
+ from .config_helper import ConfigHelpers
15
+ from toolkits.databases.mysql_helper import MysqlHelper
16
+
17
+ logger = log("EnvPrepare")
18
+
19
+
20
+ class EnvPrepare:
21
+ config_file_path = None
22
+
23
+ def __init__(self, app_name, config_full_path=None, config_global_name="config_global"):
24
+ self.__base_path = get_script_directory()
25
+ self.__config_global_name = config_global_name
26
+ self.__user_home_path = os.path.expanduser("~/.config")
27
+ self.__app_name = app_name
28
+ self.__config_full_path = None
29
+ self.__config_path = "%s/%s/" % (self.__get_workdir(), self.__app_name)
30
+ if config_full_path:
31
+ if Path(config_full_path).exists():
32
+ self.__config_full_path = config_full_path
33
+ else:
34
+ logger.error("Config was not exist:[%s]" % config_full_path)
35
+
36
+ self.__tip_message = "Initialized: finished, please change the default's config to " \
37
+ "adapt your environment! "
38
+ self.__default_path_tip = "Default config path: %s" % self.__config_path
39
+ self.__dict_config = {}
40
+
41
+ def __get_workdir(self):
42
+ app_data = self.__user_home_path
43
+ if platform.system().lower() == 'windows': # print("windows")
44
+ app_data = "%s\\.config" % os.getenv("APPDATA")
45
+ elif platform.system().lower() == 'linux': # print("linux")
46
+ app_data = self.__user_home_path
47
+ return app_data
48
+
49
+ def check_env(self):
50
+ # check env-config
51
+ if not Path(self.__config_path).exists():
52
+ Path(self.__config_path).mkdir(parents=True)
53
+ src_path = "%s/../config/" % self.__base_path
54
+ self.init_default_config("directory", src_path, self.__config_path)
55
+ print("%s\n%s" % (self.__tip_message, self.__default_path_tip))
56
+ logger.error("%s\n%s" % (self.__tip_message, self.__default_path_tip))
57
+
58
+ def check_config_ready(self, config_path, error_message):
59
+ if not Path(config_path).exists():
60
+ msg = error_message + "\n" + self.__default_path_tip
61
+ print(msg)
62
+ logger.error(msg)
63
+ # raise Exception(msg)
64
+ exit(-1)
65
+
66
+ def get_config_path(self, config_file_name):
67
+ return "%s/%s" % (self.__config_path, config_file_name)
68
+
69
+ def get_config_from_file(self, config_path: str, config_key: str, force_reload: bool = False) -> dict:
70
+ if config_path not in self.__dict_config or force_reload is True:
71
+ config_data = ConfigHelpers.load_config(config_path)
72
+ self.__dict_config[config_path] = config_data
73
+ else:
74
+ config_data = self.__dict_config[config_path]
75
+
76
+ return ConfigHelpers.get_config_by_name(config_data, config_key)
77
+
78
+ def __get_default_config_file(self):
79
+ running_app = os.path.split(os.path.realpath(sys.argv[0]))[1]
80
+ if running_app[-3:] == ".py" or running_app[-4:] == ".pyc":
81
+ path_working = os.path.split(os.path.realpath(sys.argv[0]))[0]
82
+ else:
83
+ path_working = os.getcwd()
84
+
85
+ config_path_working = "%s/config.py" % path_working
86
+ if not Path(config_path_working).exists():
87
+ config_path_working = "%s/%s/config.py" % (self.__user_home_path, self.__app_name)
88
+ return config_path_working
89
+
90
+ def get_default_config(self, config_key: str, force_reload: bool = False) -> dict:
91
+ if EnvPrepare.config_file_path:
92
+ config_path_working = EnvPrepare.config_file_path
93
+ else:
94
+ config_path_working = self.__get_default_config_file()
95
+ logger.debug("config_path_working: %s", config_path_working)
96
+ config_data = None
97
+ if Path(config_path_working).exists():
98
+ config_data = self.get_config_from_file(config_path_working, config_key, force_reload)
99
+ return config_data
100
+
101
+ def get_config(self, config_key: str, force_reload: bool = False):
102
+ if self.__config_full_path:
103
+ config_data = self.get_config_from_file(self.__config_full_path, self.__config_global_name, force_reload)
104
+ else:
105
+ config_data = self.get_default_config(self.__config_global_name, force_reload)
106
+ return jmespath.search(config_key, config_data)
107
+
108
+ @staticmethod
109
+ def init_default_config(init_type, src_path, dest_path):
110
+ init_status = False
111
+ if init_type == 'file':
112
+ if platform.system().lower() == 'windows':
113
+ cmd_copy = "XCOPY /S /-Y %s %s " % (str(src_path).replace("/", "\\"), str(dest_path).replace("/", "\\"))
114
+ elif platform.system().lower() == 'linux':
115
+ cmd_copy = "cp -arf %s %s " % (src_path, dest_path)
116
+ elif init_type == 'directory':
117
+ if platform.system().lower() == 'windows':
118
+ cmd_copy = "xcopy /S /-Y %s %s " % (str(src_path).replace("/", "\\"), str(dest_path).replace("/", "\\"))
119
+ elif platform.system().lower() == 'linux':
120
+ cmd_copy = "cp -arf %s/* %s/ " % (src_path, dest_path)
121
+ else:
122
+ return init_status
123
+
124
+ logger.info("CopyCMD: %s" % cmd_copy)
125
+ ret = exec_shell(cmd_copy)
126
+ if str(ret['exit_code']) == "0":
127
+ init_status = True
128
+ return init_status
129
+
130
+ @staticmethod
131
+ def init_db(database_config, sql_execute):
132
+ try:
133
+ mysql_conn = MysqlHelper(database_config)
134
+ mysql_conn.execute(sql_execute)
135
+ except Exception as ex:
136
+ logger.error("Error: %s" % ex)
137
+ logger.error(traceback.format_exc())
138
+
139
+
140
+ if __name__ == '__main__':
141
+ try:
142
+ fire.Fire(EnvPrepare)
143
+ except Exception as ex:
144
+ logger.error("Error: %s" % ex)
145
+ logger.error(traceback.format_exc())
@@ -0,0 +1,151 @@
1
+ # -*- coding: utf-8 -*-
2
+ import importlib
3
+ import sys
4
+ import traceback
5
+ try:
6
+ from urllib import parse
7
+ except Exception as ex:
8
+ import urllib as parse
9
+
10
+ from log4python.Log4python import log
11
+ from sqlalchemy import Engine
12
+ from sqlalchemy import create_engine
13
+ from sqlalchemy.sql import text
14
+
15
+ importlib.reload(sys)
16
+ logger = log("MysqlHelper")
17
+ import pymysql
18
+
19
+ pymysql.version_info = (1, 4, 13, "final", 0)
20
+ pymysql.install_as_MySQLdb()
21
+
22
+
23
+ class MysqlHelper:
24
+ def __init__(self, database_config=None):
25
+ self.mysql_config = database_config
26
+ self.__engine = None
27
+
28
+ def get_mysql_client(self, config_user=None) -> Engine:
29
+ '''
30
+ mysql_db = 'mysql://root:***@10.89.189.48:8027/log_etl'
31
+ '''
32
+ engine = None
33
+ try:
34
+ if self.__engine is None:
35
+ if config_user:
36
+ config_init = config_user
37
+ else:
38
+ config_init = self.mysql_config
39
+ mysql_db = 'mysql://%s:%s@%s:%s/%s?charset=utf8' % (config_init['user_name'],
40
+ parse.quote_plus(config_init['password']),
41
+ config_init['host'],
42
+ config_init['port'],
43
+ config_init['db_name']
44
+ )
45
+ engine = create_engine(mysql_db, echo=False, pool_recycle=3600, pool_pre_ping=True)
46
+ self.__engine = engine
47
+ else:
48
+ engine = self.__engine
49
+ except Exception as ex:
50
+ logger.error(traceback.format_exc())
51
+ logger.error('deal_msg error: %s' % ex)
52
+ return engine
53
+
54
+ def execute(self, sql):
55
+ try:
56
+ # 创建数据库引擎
57
+ engine = self.get_mysql_client()
58
+ # 定义SQL查询语句
59
+ execute_stmt = text(sql)
60
+ with engine.connect() as connection:
61
+ try:
62
+ result = connection.execute(execute_stmt)
63
+ connection.commit()
64
+ except Exception as e:
65
+ logger.error(traceback.format_exc())
66
+ logger.error('deal_msg error: %s' % e)
67
+ connection.rollback()
68
+ except Exception as ex:
69
+ logger.error(traceback.format_exc())
70
+ logger.error('deal_msg error: %s' % ex)
71
+
72
+ def query(self, sql) -> list[dict]:
73
+ try:
74
+ # 创建数据库引擎
75
+ engine = self.get_mysql_client()
76
+
77
+ # 定义SQL查询语句
78
+ select_stmt = text(sql)
79
+
80
+ # 使用连接执行查询
81
+ result_list = []
82
+ with engine.connect() as connection:
83
+ result = connection.execute(select_stmt)
84
+
85
+ # 将查询结果转换为字典列表
86
+ # 使用fetchall()获取所有结果行,每行是一个元组
87
+ # 使用namedtuple来获取列名和数据的对应关系
88
+ columns = result.keys()
89
+ result_list = [dict(zip(columns, row)) for row in result]
90
+ except Exception as ex:
91
+ logger.error(traceback.format_exc())
92
+ logger.error('deal_msg error: %s' % ex)
93
+ return result_list
94
+
95
+ @staticmethod
96
+ def get_insert_schema(filed_names_list):
97
+ schema_final = ""
98
+ val_data = ""
99
+ for item in filed_names_list:
100
+ schema_final = schema_final + "%s, " % item.strip()
101
+ val_data = val_data + ":%s, " % item.strip()
102
+ schema_final = schema_final.strip(" ,")
103
+ val_data = val_data.strip(" ,")
104
+ return schema_final, val_data
105
+
106
+ def bulk_insert(self, table_name: str, columns: list, data_list: list, batch_size=20000, columns_on_duplicate=[]):
107
+ """
108
+ 执行分批批量插入操作的通用函数。
109
+
110
+ :param columns_on_duplicate: 唯一键冲突时覆盖
111
+ :param table_name: 要插入数据的表名
112
+ :param columns: 表的列名列表
113
+ :param data_list: 要插入的数据列表,其中每个元素是一个包含列值的元组
114
+ :param batch_size: 每批插入的数据量
115
+ """
116
+ # 创建数据库引擎
117
+ engine = self.get_mysql_client()
118
+
119
+ on_duplicate_sql = ""
120
+ if columns_on_duplicate:
121
+ tmp_list = []
122
+ for item in columns_on_duplicate:
123
+ tmp_list.append("%s=VALUES(%s)" % (item, item))
124
+ if tmp_list:
125
+ on_duplicate_sql = "ON DUPLICATE KEY UPDATE %s" % ", ".join(tmp_list)
126
+
127
+ # 准备批量插入的SQL语句模板
128
+ schema_final, placeholders = self.get_insert_schema(columns)
129
+ insert_stmt = text(f"INSERT INTO {table_name} ({schema_final}) VALUES ({placeholders}) {on_duplicate_sql}")
130
+ logger.info("BulkInsert:[%s]" % str(insert_stmt))
131
+
132
+ try:
133
+ # 使用连接执行分批批量插入
134
+ with engine.connect() as connection:
135
+ try:
136
+ for i in range(0, len(data_list), batch_size):
137
+ # 获取当前批次的数据
138
+ batch_data = data_list[i:i + batch_size]
139
+ # 执行批量插入
140
+ connection.execute(insert_stmt, batch_data)
141
+ logger.info(f"Batch inserted {len(batch_data)} records.")
142
+
143
+ connection.commit()
144
+ logger.debug(f"Successfully inserted all data into {table_name},inserted {len(batch_data)} records.")
145
+ except Exception as e:
146
+ logger.error(traceback.format_exc())
147
+ logger.error('deal_msg error: %s' % e)
148
+ connection.rollback()
149
+ except Exception as ex:
150
+ logger.error(traceback.format_exc())
151
+ logger.error('deal_msg error: %s' % ex)
@@ -0,0 +1,71 @@
1
+ # -*- coding: utf-8 -*-
2
+ import traceback
3
+
4
+ import fire
5
+ from log4python.Log4python import log
6
+ from toolkits.system.basic_utils import get_script_directory
7
+
8
+ from toolkits.config_parser.env_prepare import EnvPrepare
9
+ from toolkits.databases.mysql_helper import MysqlHelper
10
+
11
+ logger = log("DbQueryDemo")
12
+
13
+
14
+ class DbQueryDemo:
15
+ def __init__(self, config_path=None):
16
+ self.__base_path = get_script_directory()
17
+ self.__config_path = config_path
18
+ if config_path is None:
19
+ if tookitsApp.config_file_path is None:
20
+ self.__env = EnvPrepare(tookitsApp.app_name)
21
+ self.__env.check_env()
22
+ self.__config_path = self.__env.get_config_path("config.py")
23
+ self.__env.check_config_ready(self.__config_path, "请先初始化配置文件、在数据库创建相应的数据表")
24
+ else:
25
+ self.__config_path = tookitsApp.config_file_path
26
+
27
+ self.__env = EnvPrepare(tookitsApp.app_name, self.__config_path)
28
+ self.__mysql_config = self.__env.get_config('mysql_info_online_alarm')
29
+ self.sql_helper = MysqlHelper(self.__mysql_config)
30
+
31
+ def query_sql(self, query_where) -> list:
32
+ list_api = self.sql_helper.query("SELECT x.* FROM sec_admin.api_sec_output_send x WHERE bot_process in (%s)" % query_where)
33
+ # logger.debug("Result:[%s]" % json.dumps(list_api))
34
+ logger.debug("Len: %s" % str(len(list_api)))
35
+ return list_api
36
+
37
+ @staticmethod
38
+ def __read_all_data(file_path):
39
+ fp = open(file_path)
40
+ data_list = fp.readlines()
41
+ fp.close()
42
+ ns_list = []
43
+ for item in data_list:
44
+ ns_list.append(str(item).strip())
45
+ return ns_list
46
+
47
+ def worker(self, file_path, batch_size=10):
48
+ data_list = self.__read_all_data(file_path)
49
+ final_list = []
50
+ for i in range(0, len(data_list), batch_size):
51
+ # 获取当前批次的数据
52
+ batch_data = data_list[i:i + batch_size]
53
+ sql_where = "'%s'" % "', '".join(batch_data)
54
+
55
+ kylin_list = self.query_sql(sql_where)
56
+ final_list.extend(kylin_list)
57
+
58
+ fp = open("%s.csv" % file_path, "w+")
59
+ fp.write("source,host,name_space")
60
+ for item in list(set(final_list)):
61
+ fp.write("%s,%s,%s\r\n" % (item['source'], item['host'], item['name_space']))
62
+ fp.close()
63
+
64
+
65
+ if __name__ == '__main__':
66
+ try:
67
+ fire.Fire(DbQueryDemo)
68
+ except Exception as ex:
69
+ logger.error("Error: %s" % ex)
70
+ logger.error(traceback.format_exc())
71
+