腾讯云服务器批量操作方案,请勿用于非法操作

举例在多台 Debian 12 系统的腾讯云服务器上实现 "一台操作,其余多台同步执行" 的功能。以下是几种可行的解决方案:

方案一:使用腾讯云自动化助手(TAT)

腾讯云自动化助手 (TAT) 是腾讯云提供的原生批量运维工具,可以直接在控制台或通过 API 批量执行命令。

Python代码示例

import base64
import json
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.tat.v20201028 import tat_client, models

# 配置您的腾讯云API密钥
cred = credential.Credential("SecretId", "SecretKey")

# 配置TAT客户端
httpProfile = HttpProfile()
httpProfile.endpoint = "tat.tencentcloudapi.com"
clientProfile = ClientProfile()
clientProfile.httpProfile = httpProfile

# 所有实例ID列表(替换为您的多台实例ID)
instance_ids = [
    "ins-xxxxxx1", "ins-xxxxxx2", "ins-xxxxxx3", 
    # ... 添加所有多台实例ID
]

# 要执行的命令(Base64编码)
command = "apt update && apt upgrade -y"  # 示例命令
encoded_command = base64.b64encode(command.encode('utf-8')).decode('utf-8')

# 创建并执行命令
client = tat_client.TatClient(cred, "ap-guangzhou", clientProfile)  # 替换为您的地域

try:
    # 创建命令
    req = models.RunCommandRequest()
    params = {
        "CommandName": "batch-command",
        "Content": encoded_command,
        "CommandType": "SHELL",
        "WorkingDirectory": "/root",
        "Timeout": 60,
        "InstanceIds": instance_ids
    }
    req.from_json_string(json.dumps(params))
    resp = client.RunCommand(req)
    print(resp.to_json_string())
except Exception as err:
    print(err)

方案二:使用Ansible进行批量管理

Ansible 是流行的开源批量管理工具,基于 SSH 无需在被管理端安装客户端。

1. 安装Ansible

在主控服务器上安装 Ansible:

sudo apt update
sudo apt install -y ansible

2. 配置主机清单

编辑/etc/ansible/hosts文件,添加所有服务器的 IP 地址:

[debian_servers]
192.168.1.1 ansible_user=root ansible_ssh_pass=yourpassword
192.168.1.2 ansible_user=root ansible_ssh_pass=yourpassword
192.168.1.3 ansible_user=root ansible_ssh_pass=yourpassword
...

或者使用 SSH 密钥认证更安全:

ssh-keygen
ssh-copy-id root@server_ip  # 对每台服务器执行

然后 hosts 文件可以简化为:

[debian_servers]
192.168.1.1
192.168.1.2
192.168.1.3
...

3. 测试连接

ansible all -m ping

4. 执行批量命令

# 执行单条命令
ansible all -a "apt update && apt upgrade -y"

# 执行脚本(先上传脚本到所有服务器)
ansible all -m script -a "/path/to/your_script.sh"

5. Python代码调用Ansible

import subprocess

def run_ansible_command(command):
    try:
        result = subprocess.run(
            ["ansible", "all", "-a", command],
            capture_output=True,
            text=True,
            check=True
        )
        print(result.stdout)
    except subprocess.CalledProcessError as e:
        print(f"Error executing command: {e.stderr}")

# 示例:在所有服务器上执行命令
run_ansible_command("df -h")

方案三:使用腾讯云API直接操作

直接使用腾讯云 API 批量操作服务器。

批量关机示例

from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.cvm.v20170312 import cvm_client, models

# 配置凭证
cred = credential.Credential("SecretId", "SecretKey")
httpProfile = HttpProfile()
httpProfile.endpoint = "cvm.tencentcloudapi.com"
clientProfile = ClientProfile()
clientProfile.httpProfile = httpProfile

# 实例ID列表
instance_ids = ["ins-xxxxxx1", "ins-xxxxxx2", ...]  # 替换为您的实例ID

# 创建客户端
client = cvm_client.CvmClient(cred, "ap-guangzhou", clientProfile)  # 替换地域

# 创建请求
req = models.StopInstancesRequest()
params = {
    "InstanceIds": instance_ids,
    "StopType": "SOFT"  # 软关机
}
req.from_json_string(json.dumps(params))

# 发送请求
resp = client.StopInstances(req)
print(resp.to_json_string())

最佳实践建议

  1. 安全性

    • 使用 SSH 密钥认证而非密码

    • 为 Ansible 或 API 创建专门的子账号并限制权限

    • 定期轮换 API 密钥

  2. 效率

    • 对于简单命令,Ansible 是最便捷的选择

    • 对于复杂操作,可以编写 Ansible Playbook

    • 腾讯云 TAT 适合与云服务深度集成的场景

  3. 监控

    • 使用ansible all -a "command"查看所有服务器状态

    • 腾讯云 TAT 提供命令执行结果查看功能

  4. 扩展性

    • Ansible 支持模板、变量和条件执行,适合复杂运维场景

    • 可以编写 Playbook 实现更复杂的自动化流程

以上方案都可以实现 "一台操作,其余多台同步执行" 的需求,您可以根据具体场景选择最适合的方案。


腾讯云服务器批量操作方案,请勿用于非法操作
https://uniomo.com/archives/teng-xun-yun-fu-wu-qi-pi-liang-cao-zuo-fang-an-qing-wu-yong-yu-fei-fa-cao-zuo
作者
雨落秋垣
发布于
2025年09月09日
许可协议