批量SSH执行命令脚本
批量在多台服务器上执行命令,支持并行执行,输出每台服务器的结果,运维必备。
详细内容
#!/usr/bin/env python3
# 批量SSH执行命令脚本
# 依赖: pip install paramiko
# 使用方法: python3 batch_ssh.py "命令"
import paramiko
import sys
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime
# ========== 服务器列表 ==========
SERVERS = [
{"host": "192.168.1.10", "port": 22, "user": "root", "password": "password1"},
{"host": "192.168.1.11", "port": 22, "user": "root", "password": "password2"},
# 添加更多服务器...
]
# ================================
def execute_ssh(server, command):
"""在单台服务器上执行命令"""
host = server["host"]
try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(
hostname=server["host"],
port=server.get("port", 22),
username=server["user"],
password=server["password"],
timeout=10
)
stdin, stdout, stderr = client.exec_command(command, get_pty=True)
output = stdout.read().decode('utf-8', errors='ignore')
error = stderr.read().decode('utf-8', errors='ignore')
client.close()
return host, output, error, None
except Exception as e:
return host, "", "", str(e)
def main():
if len(sys.argv) < 2:
print("使用方法: python3 batch_ssh.py \"要执行的命令\"")
print("示例: python3 batch_ssh.py \"uptime && df -h\"")
sys.exit(1)
command = sys.argv[1]
print("=" * 60)
print(f" 批量SSH执行")
print(f" 命令: {command}")
print(f" 服务器数: {len(SERVERS)}")
print(f" 时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print("=" * 60)
with ThreadPoolExecutor(max_workers=10) as executor:
results = executor.map(lambda s: execute_ssh(s, command), SERVERS)
for host, output, error, conn_error in results:
print(f"\n{'─' * 40}")
print(f"📡 {host}")
print(f"{'─' * 40}")
if conn_error:
print(f" ❌ 连接失败: {conn_error}")
else:
if output.strip():
print(output.strip())
if error.strip():
print(f" ⚠️ 错误输出: {error.strip()}")
print(f"\n{'=' * 60}")
print(" 执行完成")
print(f"{'=' * 60}")
if __name__ == '__main__':
main()