python
from concurrent.futures import ThreadPoolExecutor, as_completed
import random
import time
# 假设您的发送SNMP请求的函数如下
def send_snmp_command(device_info, command):
"""
发送SNMP命令到设备的函数,这里用随机成功和失败来模拟实际情况。
返回True表示成功,False表示失败。
"""
print(f"Sending '{command}' to device: {device_info}")
time.sleep(1) # 模拟网络延迟
return random.choice([True, False])
def execute_commands(device_commands):
"""
device_commands格式:[(device_info, command), ...]
"""
success_count = 0
fail_count = 0
with ThreadPoolExecutor(max_workers=1) as executor:
# 提交所有任务
future_to_command = {executor.submit(send_snmp_command, dc[0], dc[1]): dc for dc in device_commands}
# 等待所有任务完成并处理结果
for future in as_completed(future_to_command):
command = future_to_command[future]
try:
result = future.result()
if result:
print(f"Command {command} executed successfully.")
success_count += 1
else:
print(f"Command {command} failed.")
fail_count += 1
except Exception as exc:
print(f"Command {command} generated an exception: {exc}.")
fail_count += 1
return success_count, fail_count
# 示例使用
device_commands = [
(('192.168.1.1', 'community'), 'get sysDescr.0'),
(('192.168.1.2', 'community'), 'get ifDescr.1'),
]
success_count, fail_count = execute_commands(device_commands)
print(f"总共成功{success_count}个, 总共失败{fail_count}个.")