import paramiko # 设置SSH连接参数 port = 22 username = 'root' password = 'alpine' def execute_command(hostname: str, command: str): # 创建SSH客户端 client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 连接SSH服务端 client.connect(hostname, port, username, password) # 执行命令 stdin, stdout, stderr = client.exec_command(command) output = stdout.read().decode('utf-8') error = stderr.read().decode('utf-8') print(f"主机 {hostname} 执行命令: {command}") if output: print("输出:", output) if error: print("错误:", error) # 关闭连接 client.close() if __name__ == "__main__": ips1 = [] with open("./ips.txt", 'r') as f: ips1 = [i.strip() for i in f.readlines()] command = 'ls -l' # 替换为实际要执行的命令 for hostname in ips1: try: print(hostname) execute_command(hostname, command) except Exception as e: print(e)