Python 运维自动化:从 paramiko 到 Ansible
paramiko:SSH 批量管理基础 paramiko 是 Python 实现的 SSHv2 协议库,是运维自动化的底层基石。当需要精细控制 SSH 连接、处理非标准场景时,paramiko 提供了最大灵活性。 基础连接与命令执行 import paramiko import time def ssh_exec(host, port, username, password, command): """基础 SSH 命令执行""" client = paramiko.SSHClient() # 自动添加主机密钥(生产环境建议使用 known_hosts) client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: client.connect(host, port=port, username=username, password=password, timeout=10) stdin, stdout, stderr = client.exec_command(command) # 获取退出码 exit_code = stdout.channel.recv_exit_status() output = stdout.read().decode().strip() error = stderr.read().decode().strip() return { 'host': host, 'exit_code': exit_code, 'output': output, 'error': error } finally: client.close() # 使用示例 result = ssh_exec('10....