fabric批量控制VPS运行脚本

Python · 5 天前 · 7 人浏览

使用fabric来批量控制VPS运行脚本:

from fabric import Connection, Config
from loguru import logger
# 服务器列表(包含密码)
servers = [
    {"host": "1223:3333:103:218::32", "user": "root", "port": 22, "password": "your_password_1"},
    # {"host": "192.168.1.102", "user": "root", "port": 2222, "password": "your_password_2"}
]
comm = input('请输入命令(回车跳过):')
comm = comm if comm else "echo 'Echo test'"
def run_command(host, user, port, password, command):
    # 配置连接参数
    config = Config(overrides={
        'connect_kwargs': {'password': password},
        'sudo': {'password': password}  # 如果需要sudo
    })
    try:
        with Connection(
                host=host,
                user=user,
                port=port,
                config=config,
                connect_timeout=10,
        ) as conn:
            result = conn.run(command, hide=False, encoding='utf-8')
            print(f"[SUCCESS] {host}: {result.stdout.strip()}")
    except Exception as e:
        print(f"[FAILED] {host}: {str(e)}")
        return False
    return True

# 批量执行命令
for server in servers:
    res = run_command(
        server["host"],
        server["user"],
        server.get("port", 22),  # 默认SSH端口
        server["password"],
        comm  # 示例命令
    )
    logger.error(server) if not(res) else None
本站立足于美利堅合衆國,請讀者自覺遵守當地法律!如有違規,本站不承擔任何法律責任! This site is based in the United States of America, readers are requested to abide by local laws! If there are any violations, this site does not bear any legal responsibility! Theme Jasmine by Kent Liao