1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
| import paramiko from concurrent.futures import ThreadPoolExecutor, as_completed import os
ip_file = "ip.list" username = "root" password = "123456" command = "hostname" max_workers = 50
def load_ip_list(filepath): try: with open(filepath, "r") as f: return [line.strip() for line in f if line.strip()] except FileNotFoundError: print(f"IP 列表文件 '{filepath}' 不存在") exit(1)
def run_command(ip): try: ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip, username=username, password=password, timeout=5)
stdin, stdout, stderr = ssh.exec_command(command) result = stdout.read().decode().strip() error = stderr.read().decode().strip() ssh.close()
return (ip, result if result else error) except Exception as e: return (ip, f"连接失败: {e}")
def get_completed_ips(filepath): """从result.list中读取已完成的IP""" if not os.path.exists(filepath): return set() with open(filepath, "r") as f: return {line.split("=>")[0].strip() for line in f if "=>" in line}
def main(): ip_list = load_ip_list(ip_file) completed_ips = get_completed_ips("result.list") ip_list_to_run = [ip for ip in ip_list if ip not in completed_ips]
total = len(ip_list) to_run = len(ip_list_to_run) if to_run == 0: print("所有 IP 已完成,无需重复执行") return
print(f"共 {total} 个 IP,已完成 {total - to_run} 个,剩余 {to_run} 个待执行\n")
with open("result.list", "a") as good_file, open("badip.list", "a") as bad_file: with ThreadPoolExecutor(max_workers=max_workers) as executor: future_to_ip = {executor.submit(run_command, ip): ip for ip in ip_list_to_run} finished = 0 for future in as_completed(future_to_ip): ip, output = future.result()
if output.startswith("连接失败"): bad_file.write(f"{ip}\n") else: single_line_output = " ".join(line.strip() for line in output.splitlines()) good_file.write(f"{ip} => {single_line_output}\n")
finished += 1 print(f"[{finished}/{to_run}] 已完成 {ip}")
if __name__ == "__main__": main()
|