Skip to main content

批量SSH操作和文件传输工具包,提升了解码兼容能力

Project description

GINKGO-TOOLS-BATCHSSH

一个用于批量SSH操作和文件传输的Python工具包。

功能特性

  • 🔧 SSH连接管理 - 简化SSH连接建立和管理
  • 远程命令执行 - 支持超时控制的远程命令执行
  • 📁 SFTP文件传输 - 支持通配符的批量文件上传下载
  • 🎯 批量主机操作 - 支持多主机并行操作
  • 📝 智能日志系统 - 自动记录操作日志便于追踪
  • 🛠️ 便捷工具函数 - 提供常用的主机管理和过滤工具

安装

pip install ginkgo_tools_batchssh

快速开始

基本SSH连接和命令执行

from ginkgo_tools_batchssh import SSHWrapper

# 创建SSH连接
ssh = SSHWrapper(
    host_ip="192.168.1.100",
    username="your_username",
    password="your_password"
)

# 执行单个命令
result = ssh.execute_command("ls -la")
print(f"执行结果: {result['result']}")
print(f"输出内容: {result['stdout']}")

# 执行多个命令
commands = ["cd /tmp", "pwd", "ls"]
result = ssh.execute_shell_commands(commands)
print(result['stdout'])

文件传输操作

# 上传单个文件
upload_result = ssh.sftp_upload_file("local_file.txt", "/remote/path/file.txt")

# 批量上传文件(支持通配符)
upload_result = ssh.sftp_upload_to("*.log", "/remote/logs/")

# 下载文件
download_result = ssh.sftp_download_file("/remote/file.txt", "local_file.txt")

# 批量下载文件(支持通配符)
download_result = ssh.sftp_download_to("/remote/logs/*.log", "./local_logs/")

主机管理工具

from ginkgo_tools_batchssh import read_hosts_file, parse_and_filter_hosts

# 读取hosts文件
hosts_content = read_hosts_file()

# 过滤和解析主机
filter_list = ["web", "server"]  # 只选择包含这些关键词的主机
target_hosts = parse_and_filter_hosts(hosts_content, filter_list)

# target_hosts 格式: {"ip_address": ["hostname1", "hostname2"]}
for ip, hostnames in target_hosts.items():
    print(f"{ip}: {', '.join(hostnames)}")

核心组件

SSHWrapper 类

主要的SSH操作类,提供以下核心功能:

  • ssh_connect() - 建立SSH连接
  • execute_command() - 执行单个命令
  • execute_shell_commands() - 执行多个命令
  • sftp_upload_*() - 文件上传相关方法
  • sftp_download_*() - 文件下载相关方法
  • commands_to_shell_*() - Shell脚本执行相关方法

便捷工具函数

  • read_hosts_file() - 读取hosts文件内容
  • parse_and_filter_hosts() - 解析和过滤主机列表

日志系统

  • setup_logging() - 配置日志系统
  • get_logger() - 获取日志记录器

高级用法

超时控制

# 设置命令执行超时时间(秒)
result = ssh.execute_command("sleep 60", timeout=30)
if result['do_break']:
    print("命令执行超时")

Shell脚本执行

# 将命令封装为shell脚本并执行
commands = [
    "echo '开始执行任务'",
    "date",
    "ls -la"
]

# 传输脚本文件
trans_result = ssh.commands_to_shell_trans(command_list=commands)

# 执行脚本(可选sudo切换用户)
exec_result = ssh.commands_to_shell_run(trans_result, sudo_to_user="root")

批量主机操作示例

from ginkgo_tools_batchssh import SSHWrapper, read_hosts_file, parse_and_filter_hosts

# 获取目标主机列表
hosts_content = read_hosts_file()
target_hosts = parse_and_filter_hosts(hosts_content, ["production"])

# 批量执行操作
results = {}
for ip, hostnames in target_hosts.items():
    try:
        ssh = SSHWrapper(
            host_ip=ip,
            username="admin",
            password="password",
            host_name=hostnames[0]
        )
        
        result = ssh.execute_command("uptime")
        results[ip] = result
        
        ssh.close()
    except Exception as e:
        results[ip] = {"result": False, "error": str(e)}

# 查看结果
for ip, result in results.items():
    if result['result']:
        print(f"{ip}: {result['stdout'].strip()}")
    else:
        print(f"{ip}: 执行失败 - {result.get('error', '未知错误')}")

返回值格式

大多数方法返回统一的字典格式:

{
    "result": True/False,           # 操作是否成功
    "stdout": "输出内容",            # 标准输出
    "stderr": "错误内容",            # 错误输出
    "exit_status": 0,               # 退出状态码
    "error": "错误信息",             # 错误描述(失败时)
    # 其他特定字段...
}

依赖要求

  • Python >= 3.8
  • paramiko >= 2.7.0

许可证

MIT License

作者

霍城 495466557@qq.com


注意:请根据实际使用场景调整连接参数和安全设置

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ginkgo_tools_batchssh-0.1.6.tar.gz (15.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ginkgo_tools_batchssh-0.1.6-py3-none-any.whl (14.4 kB view details)

Uploaded Python 3

File details

Details for the file ginkgo_tools_batchssh-0.1.6.tar.gz.

File metadata

  • Download URL: ginkgo_tools_batchssh-0.1.6.tar.gz
  • Upload date:
  • Size: 15.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.9

File hashes

Hashes for ginkgo_tools_batchssh-0.1.6.tar.gz
Algorithm Hash digest
SHA256 d7512a1928256db45a94b7427a3ddf00a1025e4c01db9fd720a8a4335dc7e3c2
MD5 64aed07d1d300e56cda5b602c05e6921
BLAKE2b-256 492aaab876cd0e20a93d48d9bf3cce2d03eb8d1f71b2080c3e5b6d4a3572cc7d

See more details on using hashes here.

File details

Details for the file ginkgo_tools_batchssh-0.1.6-py3-none-any.whl.

File metadata

File hashes

Hashes for ginkgo_tools_batchssh-0.1.6-py3-none-any.whl
Algorithm Hash digest
SHA256 da74752ebacd0de0ba17be1c92ac00e10546cafed35ce51e12b679a1d4e88bef
MD5 f2f63ff52e88ee0202bb2f2d90d6bb09
BLAKE2b-256 e8efc3592089bf8cdad9f9ee0e56a230156c1fb52994a7f8e9ba1c22ae9801f9

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page