在上一節中,已經實現依次登入設備庫中的交換機。如果設備庫的數量少,那等待的時間可以忽略,但如果有50台以上的設備要操作,那就必須要考慮效率問題了。所以,使用到綫程池這個功能,實現同時登入多台設備,同時限制綫程數量,確保操作過程高效且穩定。
以下代碼使用裝飾器和綫程池,請自行查閲相關資料:)
import yaml
from netmiko import ConnectHandler
from netmiko.exceptions import NetmikoTimeoutException, NetmikoAuthenticationException
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
# 裝飾器,用於計算所耗時間
def run_time(func):
def wrapper(*args, **kwargs):
start = time.time()
func(*args, **kwargs)
print("TIME: ", time.time() - start)
return wrapper
# ssh連接交換機進行操作
def ssh_dev(hostname, conn_info):
cmd_cisco = [
'show run',
'show inventory'
]
cmd_huawei = [
'display cu',
'display startup'
]
cmd_extreme = [
'show conf'
]
try:
with ConnectHandler(**conn_info) as conn:
# print(f'[{hostname}] connected -> {conn.find_prompt()}')
cmds= []
if conn_info['device_type'] == "extreme_exos":
cmds = cmd_extreme
elif conn_info['device_type'] == "cisco_ios":
cmds = cmd_cisco
elif conn_info['device_type'] == "huawei":
cmds = cmd_huawei
for c in cmds:
output = conn.send_command_timing(c)
# print(output)
except NetmikoTimeoutException:
print(f'ERROR: [{hostname}] connect timeout!')
except NetmikoAuthenticationException:
print(f'ERROR: [{hostname}] please check your username & password!')
return f"[{hostname}] finished."
# 語法糖,對main計算時間
@run_time
def main(devs):
# max_workers指定綫程數量
with ThreadPoolExecutor(max_workers=5) as pool:
futures = [pool.submit(ssh_dev, k, v) for k, v in devs.items()]
# 按列表順序顯示結果
# for future in futures:
# print(future.result())
# 先完成的結果先顯示
for future in as_completed(futures):
print(future.result())
if __name__ == '__main__':
with open('inventory.yml', 'r') as f:
devs = yaml.safe_load(f)
main(devs)