import asyncssh import sys import asyncio async def run_ssh_command(host, username, command, password, port=22): """ 异步SSH连接并执行命令,流式输出结果 参数: host: SSH服务器主机名或IP username: SSH用户名 command: 要执行的命令 password: SSH密码 key_path: SSH私钥路径 port: SSH端口号 返回: exit_code: 命令的退出码 """ print(f"正在连接到 {username}@{host}:{port}...") try: async with asyncssh.connect( host=host, port=port, username=username, password=password, known_hosts=None ) as conn: print(f"连接成功!正在执行命令: {command}") # 创建进程 process = await conn.create_process(command) # 处理标准输出流 while line := await process.stdout.readline(): print(line.rstrip(), flush=True) # 处理标准错误流 while line := await process.stderr.readline(): print(line.rstrip(), file=sys.stderr, flush=True) # 等待进程完成并获取退出状态 exit_code = await process.wait() print(f"\n命令执行完成,退出码: {exit_code}") return exit_code except (OSError, asyncssh.Error) as exc: error_msg = f"SSH连接或执行错误: {str(exc)}" print(error_msg, file=sys.stderr) return -1 def clear_ios(ip): asyncio.run(run_ssh_command(ip, "root", "rm -rfv /private/var/mobile/Containers/Data/PluginKitPlugin/*/tmp/", "alpine")) if __name__ == "__main__": with open('./ips.txt', 'r') as f: for line in f: ip = line.strip() print(ip) clear_ios(ip)