ginkgo-tools-batchssh 0.1.0__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.
@@ -0,0 +1,218 @@
1
+ Metadata-Version: 2.4
2
+ Name: ginkgo-tools-batchssh
3
+ Version: 0.1.0
4
+ Summary: 批量SSH操作和文件传输工具包
5
+ Author-email: 霍城 <495466557@qq.com>
6
+ Maintainer-email: 霍城 <495466557@qq.com>
7
+ License: MIT
8
+ Keywords: ssh,sftp,batch,automation,remote
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.8
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Classifier: Topic :: System :: Systems Administration
21
+ Classifier: Topic :: Utilities
22
+ Requires-Python: >=3.8
23
+ Description-Content-Type: text/markdown
24
+ Requires-Dist: paramiko>=2.7.0
25
+
26
+ # GINKGO-TOOLS-BATCHSSH
27
+
28
+ 一个用于批量SSH操作和文件传输的Python工具包。
29
+
30
+ ## 功能特性
31
+
32
+ - 🔧 **SSH连接管理** - 简化SSH连接建立和管理
33
+ - ⚡ **远程命令执行** - 支持超时控制的远程命令执行
34
+ - 📁 **SFTP文件传输** - 支持通配符的批量文件上传下载
35
+ - 🎯 **批量主机操作** - 支持多主机并行操作
36
+ - 📝 **智能日志系统** - 自动记录操作日志便于追踪
37
+ - 🛠️ **便捷工具函数** - 提供常用的主机管理和过滤工具
38
+
39
+ ## 安装
40
+
41
+ ```bash
42
+ pip install ginkgo_tools_batchssh
43
+ ```
44
+
45
+ ## 快速开始
46
+
47
+ ### 基本SSH连接和命令执行
48
+
49
+ ```python
50
+ from ginkgo_tools_batchssh import SSHWrapper
51
+
52
+ # 创建SSH连接
53
+ ssh = SSHWrapper(
54
+ host_ip="192.168.1.100",
55
+ username="your_username",
56
+ password="your_password"
57
+ )
58
+
59
+ # 执行单个命令
60
+ result = ssh.execute_command("ls -la")
61
+ print(f"执行结果: {result['result']}")
62
+ print(f"输出内容: {result['stdout']}")
63
+
64
+ # 执行多个命令
65
+ commands = ["cd /tmp", "pwd", "ls"]
66
+ result = ssh.execute_shell_commands(commands)
67
+ print(result['stdout'])
68
+ ```
69
+
70
+ ### 文件传输操作
71
+
72
+ ```python
73
+ # 上传单个文件
74
+ upload_result = ssh.sftp_upload_file("local_file.txt", "/remote/path/file.txt")
75
+
76
+ # 批量上传文件(支持通配符)
77
+ upload_result = ssh.sftp_upload_to("*.log", "/remote/logs/")
78
+
79
+ # 下载文件
80
+ download_result = ssh.sftp_download_file("/remote/file.txt", "local_file.txt")
81
+
82
+ # 批量下载文件(支持通配符)
83
+ download_result = ssh.sftp_download_to("/remote/logs/*.log", "./local_logs/")
84
+ ```
85
+
86
+ ### 主机管理工具
87
+
88
+ ```python
89
+ from ginkgo_tools_batchssh import read_hosts_file, parse_and_filter_hosts
90
+
91
+ # 读取hosts文件
92
+ hosts_content = read_hosts_file()
93
+
94
+ # 过滤和解析主机
95
+ filter_list = ["web", "server"] # 只选择包含这些关键词的主机
96
+ target_hosts = parse_and_filter_hosts(hosts_content, filter_list)
97
+
98
+ # target_hosts 格式: {"ip_address": ["hostname1", "hostname2"]}
99
+ for ip, hostnames in target_hosts.items():
100
+ print(f"{ip}: {', '.join(hostnames)}")
101
+ ```
102
+
103
+ ## 核心组件
104
+
105
+ ### SSHWrapper 类
106
+
107
+ 主要的SSH操作类,提供以下核心功能:
108
+
109
+ - `ssh_connect()` - 建立SSH连接
110
+ - `execute_command()` - 执行单个命令
111
+ - `execute_shell_commands()` - 执行多个命令
112
+ - `sftp_upload_*()` - 文件上传相关方法
113
+ - `sftp_download_*()` - 文件下载相关方法
114
+ - `commands_to_shell_*()` - Shell脚本执行相关方法
115
+
116
+ ### 便捷工具函数
117
+
118
+ - `read_hosts_file()` - 读取hosts文件内容
119
+ - `parse_and_filter_hosts()` - 解析和过滤主机列表
120
+
121
+ ### 日志系统
122
+
123
+ - `setup_logging()` - 配置日志系统
124
+ - `get_logger()` - 获取日志记录器
125
+
126
+ ## 高级用法
127
+
128
+ ### 超时控制
129
+
130
+ ```python
131
+ # 设置命令执行超时时间(秒)
132
+ result = ssh.execute_command("sleep 60", timeout=30)
133
+ if result['do_break']:
134
+ print("命令执行超时")
135
+ ```
136
+
137
+ ### Shell脚本执行
138
+
139
+ ```python
140
+ # 将命令封装为shell脚本并执行
141
+ commands = [
142
+ "echo '开始执行任务'",
143
+ "date",
144
+ "ls -la"
145
+ ]
146
+
147
+ # 传输脚本文件
148
+ trans_result = ssh.commands_to_shell_trans(command_list=commands)
149
+
150
+ # 执行脚本(可选sudo切换用户)
151
+ exec_result = ssh.commands_to_shell_run(trans_result, sudo_to_user="root")
152
+ ```
153
+
154
+ ### 批量主机操作示例
155
+
156
+ ```python
157
+ from ginkgo_tools_batchssh import SSHWrapper, read_hosts_file, parse_and_filter_hosts
158
+
159
+ # 获取目标主机列表
160
+ hosts_content = read_hosts_file()
161
+ target_hosts = parse_and_filter_hosts(hosts_content, ["production"])
162
+
163
+ # 批量执行操作
164
+ results = {}
165
+ for ip, hostnames in target_hosts.items():
166
+ try:
167
+ ssh = SSHWrapper(
168
+ host_ip=ip,
169
+ username="admin",
170
+ password="password",
171
+ host_name=hostnames[0]
172
+ )
173
+
174
+ result = ssh.execute_command("uptime")
175
+ results[ip] = result
176
+
177
+ ssh.close()
178
+ except Exception as e:
179
+ results[ip] = {"result": False, "error": str(e)}
180
+
181
+ # 查看结果
182
+ for ip, result in results.items():
183
+ if result['result']:
184
+ print(f"{ip}: {result['stdout'].strip()}")
185
+ else:
186
+ print(f"{ip}: 执行失败 - {result.get('error', '未知错误')}")
187
+ ```
188
+
189
+ ## 返回值格式
190
+
191
+ 大多数方法返回统一的字典格式:
192
+
193
+ ```python
194
+ {
195
+ "result": True/False, # 操作是否成功
196
+ "stdout": "输出内容", # 标准输出
197
+ "stderr": "错误内容", # 错误输出
198
+ "exit_status": 0, # 退出状态码
199
+ "error": "错误信息", # 错误描述(失败时)
200
+ # 其他特定字段...
201
+ }
202
+ ```
203
+
204
+ ## 依赖要求
205
+
206
+ - Python >= 3.8
207
+ - paramiko >= 2.7.0
208
+
209
+ ## 许可证
210
+
211
+ MIT License
212
+
213
+ ## 作者
214
+
215
+ 霍城 <495466557@qq.com>
216
+
217
+ ---
218
+ *注意:请根据实际使用场景调整连接参数和安全设置*
@@ -0,0 +1,193 @@
1
+ # GINKGO-TOOLS-BATCHSSH
2
+
3
+ 一个用于批量SSH操作和文件传输的Python工具包。
4
+
5
+ ## 功能特性
6
+
7
+ - 🔧 **SSH连接管理** - 简化SSH连接建立和管理
8
+ - ⚡ **远程命令执行** - 支持超时控制的远程命令执行
9
+ - 📁 **SFTP文件传输** - 支持通配符的批量文件上传下载
10
+ - 🎯 **批量主机操作** - 支持多主机并行操作
11
+ - 📝 **智能日志系统** - 自动记录操作日志便于追踪
12
+ - 🛠️ **便捷工具函数** - 提供常用的主机管理和过滤工具
13
+
14
+ ## 安装
15
+
16
+ ```bash
17
+ pip install ginkgo_tools_batchssh
18
+ ```
19
+
20
+ ## 快速开始
21
+
22
+ ### 基本SSH连接和命令执行
23
+
24
+ ```python
25
+ from ginkgo_tools_batchssh import SSHWrapper
26
+
27
+ # 创建SSH连接
28
+ ssh = SSHWrapper(
29
+ host_ip="192.168.1.100",
30
+ username="your_username",
31
+ password="your_password"
32
+ )
33
+
34
+ # 执行单个命令
35
+ result = ssh.execute_command("ls -la")
36
+ print(f"执行结果: {result['result']}")
37
+ print(f"输出内容: {result['stdout']}")
38
+
39
+ # 执行多个命令
40
+ commands = ["cd /tmp", "pwd", "ls"]
41
+ result = ssh.execute_shell_commands(commands)
42
+ print(result['stdout'])
43
+ ```
44
+
45
+ ### 文件传输操作
46
+
47
+ ```python
48
+ # 上传单个文件
49
+ upload_result = ssh.sftp_upload_file("local_file.txt", "/remote/path/file.txt")
50
+
51
+ # 批量上传文件(支持通配符)
52
+ upload_result = ssh.sftp_upload_to("*.log", "/remote/logs/")
53
+
54
+ # 下载文件
55
+ download_result = ssh.sftp_download_file("/remote/file.txt", "local_file.txt")
56
+
57
+ # 批量下载文件(支持通配符)
58
+ download_result = ssh.sftp_download_to("/remote/logs/*.log", "./local_logs/")
59
+ ```
60
+
61
+ ### 主机管理工具
62
+
63
+ ```python
64
+ from ginkgo_tools_batchssh import read_hosts_file, parse_and_filter_hosts
65
+
66
+ # 读取hosts文件
67
+ hosts_content = read_hosts_file()
68
+
69
+ # 过滤和解析主机
70
+ filter_list = ["web", "server"] # 只选择包含这些关键词的主机
71
+ target_hosts = parse_and_filter_hosts(hosts_content, filter_list)
72
+
73
+ # target_hosts 格式: {"ip_address": ["hostname1", "hostname2"]}
74
+ for ip, hostnames in target_hosts.items():
75
+ print(f"{ip}: {', '.join(hostnames)}")
76
+ ```
77
+
78
+ ## 核心组件
79
+
80
+ ### SSHWrapper 类
81
+
82
+ 主要的SSH操作类,提供以下核心功能:
83
+
84
+ - `ssh_connect()` - 建立SSH连接
85
+ - `execute_command()` - 执行单个命令
86
+ - `execute_shell_commands()` - 执行多个命令
87
+ - `sftp_upload_*()` - 文件上传相关方法
88
+ - `sftp_download_*()` - 文件下载相关方法
89
+ - `commands_to_shell_*()` - Shell脚本执行相关方法
90
+
91
+ ### 便捷工具函数
92
+
93
+ - `read_hosts_file()` - 读取hosts文件内容
94
+ - `parse_and_filter_hosts()` - 解析和过滤主机列表
95
+
96
+ ### 日志系统
97
+
98
+ - `setup_logging()` - 配置日志系统
99
+ - `get_logger()` - 获取日志记录器
100
+
101
+ ## 高级用法
102
+
103
+ ### 超时控制
104
+
105
+ ```python
106
+ # 设置命令执行超时时间(秒)
107
+ result = ssh.execute_command("sleep 60", timeout=30)
108
+ if result['do_break']:
109
+ print("命令执行超时")
110
+ ```
111
+
112
+ ### Shell脚本执行
113
+
114
+ ```python
115
+ # 将命令封装为shell脚本并执行
116
+ commands = [
117
+ "echo '开始执行任务'",
118
+ "date",
119
+ "ls -la"
120
+ ]
121
+
122
+ # 传输脚本文件
123
+ trans_result = ssh.commands_to_shell_trans(command_list=commands)
124
+
125
+ # 执行脚本(可选sudo切换用户)
126
+ exec_result = ssh.commands_to_shell_run(trans_result, sudo_to_user="root")
127
+ ```
128
+
129
+ ### 批量主机操作示例
130
+
131
+ ```python
132
+ from ginkgo_tools_batchssh import SSHWrapper, read_hosts_file, parse_and_filter_hosts
133
+
134
+ # 获取目标主机列表
135
+ hosts_content = read_hosts_file()
136
+ target_hosts = parse_and_filter_hosts(hosts_content, ["production"])
137
+
138
+ # 批量执行操作
139
+ results = {}
140
+ for ip, hostnames in target_hosts.items():
141
+ try:
142
+ ssh = SSHWrapper(
143
+ host_ip=ip,
144
+ username="admin",
145
+ password="password",
146
+ host_name=hostnames[0]
147
+ )
148
+
149
+ result = ssh.execute_command("uptime")
150
+ results[ip] = result
151
+
152
+ ssh.close()
153
+ except Exception as e:
154
+ results[ip] = {"result": False, "error": str(e)}
155
+
156
+ # 查看结果
157
+ for ip, result in results.items():
158
+ if result['result']:
159
+ print(f"{ip}: {result['stdout'].strip()}")
160
+ else:
161
+ print(f"{ip}: 执行失败 - {result.get('error', '未知错误')}")
162
+ ```
163
+
164
+ ## 返回值格式
165
+
166
+ 大多数方法返回统一的字典格式:
167
+
168
+ ```python
169
+ {
170
+ "result": True/False, # 操作是否成功
171
+ "stdout": "输出内容", # 标准输出
172
+ "stderr": "错误内容", # 错误输出
173
+ "exit_status": 0, # 退出状态码
174
+ "error": "错误信息", # 错误描述(失败时)
175
+ # 其他特定字段...
176
+ }
177
+ ```
178
+
179
+ ## 依赖要求
180
+
181
+ - Python >= 3.8
182
+ - paramiko >= 2.7.0
183
+
184
+ ## 许可证
185
+
186
+ MIT License
187
+
188
+ ## 作者
189
+
190
+ 霍城 <495466557@qq.com>
191
+
192
+ ---
193
+ *注意:请根据实际使用场景调整连接参数和安全设置*
@@ -0,0 +1,53 @@
1
+ """
2
+ GINKGO-TOOLS-BATCHSSH
3
+ =====================
4
+
5
+ 一个用于批量SSH操作和文件传输的Python工具包。
6
+
7
+ 主要功能:
8
+ - SSH连接管理
9
+ - 远程命令执行(支持超时控制)
10
+ - SFTP文件上传下载(支持通配符)
11
+ - 批量主机管理
12
+ - 日志记录系统
13
+
14
+ 模块说明:
15
+ - SSHWrapper: 核心SSH连接和操作类
16
+ - module_logger: 日志配置和管理模块
17
+ - moduel_convenient_tools: 便捷工具函数集合
18
+
19
+ 作者: 霍城
20
+ 邮箱: 495466557@qq.com
21
+ """
22
+
23
+ __version__ = "0.1.0"
24
+ __author__ = "霍城"
25
+ __email__ = "495466557@qq.com"
26
+ __description__ = "批量SSH操作和文件传输工具包"
27
+
28
+ # 核心类导入
29
+
30
+ from .module_SSHwrapper import SSHWrapper
31
+ from .moduel_convenient_tools import read_hosts_file, parse_and_filter_hosts
32
+ from .module_logger import setup_logging, get_logger
33
+
34
+
35
+ # 定义公共API
36
+ __all__ = [
37
+ # 核心类
38
+ 'SSHWrapper',
39
+
40
+ # 便捷工具函数
41
+ 'read_hosts_file',
42
+ 'parse_and_filter_hosts',
43
+
44
+ # 日志相关
45
+ 'setup_logging',
46
+ 'get_logger',
47
+
48
+ # 版本信息
49
+ '__version__',
50
+ '__author__',
51
+ '__email__',
52
+ '__description__'
53
+ ]
@@ -0,0 +1,51 @@
1
+ import os
2
+
3
+ """读取hosts文件,优先以当前目录下的Hosts为准,如果不存在,则读取/etc/hosts"""
4
+ def read_hosts_file(local_host_dir: str = None) -> str:
5
+ """读取hosts文件内容"""
6
+ local_host = os.path.join(local_host_dir, "hosts")
7
+ try:
8
+ with open(local_host, "r", encoding="utf-8") as f:
9
+ return f.read()
10
+ except:
11
+ with open("/etc/hosts", "r", encoding="utf-8") as f:
12
+ return f.read()
13
+
14
+
15
+
16
+
17
+ """过滤操作对象的主机地址列表,并执行去重和反向主机名匹配"""
18
+
19
+
20
+ def parse_and_filter_hosts(hosts_content: str, filter_list: list) -> dict:
21
+ """解析并过滤hosts文件内容"""
22
+ """输入的content可以是read_hosts_file()的值,也可以是手动生成的字符串,保证是ip host1 host2的行格式即可"""
23
+ target_hosts = {}
24
+
25
+ for line_num, line in enumerate(hosts_content.splitlines(), 1):
26
+ # 跳过注释行和空行
27
+ line = line.strip()
28
+ if not line or line.startswith("#"): continue
29
+
30
+ # 解析行内容
31
+ parts = line.split()
32
+ if len(parts) < 2: continue
33
+
34
+ ip_address, *hostnames = parts
35
+
36
+ # 跳过本地回环地址
37
+ if ip_address in ("127.0.0.1", "::1"): continue
38
+ # 应用过滤条件
39
+ if filter_list and not all(filter_word in line for filter_word in filter_list): continue
40
+ # 合并主机名(去重)
41
+ if ip_address in target_hosts:
42
+ target_hosts[ip_address].extend(hostnames)
43
+ else:
44
+ target_hosts[ip_address] = hostnames.copy()
45
+ return target_hosts
46
+
47
+
48
+
49
+
50
+
51
+