如何通过Tkinter按钮调用其他py文件的netmiko ConnectHandler并获取输出
问题1解决:避免scripter.py导入时自动执行
将scripter.py中的所有执行逻辑封装为函数,仅在主动调用时才触发设备连接和命令执行,同时通过函数返回值传递执行结果,解决结果回传问题。
修改后的scripter.py代码:
from netmiko import ConnectHandler def run_fortinet_command(cmd_list): fortinet_device = { 'device_type': 'fortinet', 'ip': 'X.X.X.X', 'username': 'Username', 'password': 'Password' } # 仅函数调用时才会执行连接逻辑 net_connect = ConnectHandler(**fortinet_device) output = '' for command in cmd_list: output += net_connect.send_command(command) net_connect.disconnect() return output
问题2解决:Tkinter界面添加执行按钮和结果显示区
修改main.py,新增执行按钮绑定点击回调,新增文本控件显示执行结果,点击按钮时调用scripter中的函数获取结果并渲染到界面。
修改后的main.py代码:
from tkinter import * from scripter import run_fortinet_command master = Tk(className="Test") master.geometry("600x400") # 执行按钮回调函数 def run_selected_script(): # 获取下拉框选中的参数 selected_cmd = main_menu.get() grep_rule = dependent_menu.get() # 拼接执行命令,可根据实际需求调整组合逻辑 full_cmd = [f"{selected_cmd} {grep_rule}"] if grep_rule.strip() else [selected_cmd] # 调用scripter执行逻辑获取结果 exec_result = run_fortinet_command(full_cmd) # 写入文本控件展示 output_text.delete(1.0, END) output_text.insert(END, exec_result) # 下拉框变量定义 main_menu = StringVar(master) dependent_menu = StringVar(master) # 下拉框可选值定义 show_arp = 'get sys arp' show_add = 'show firewall address' grep = '|grep' # 下拉框默认值设置 main_menu.set(show_arp) dependent_menu.set(grep) # 组件布局 OptionMenu(master, main_menu, show_arp, show_add, "three").pack(side=TOP, pady=5) OptionMenu(master, dependent_menu, grep).pack(side=TOP, pady=5) Button(master, text="执行脚本", command=run_selected_script, bg="#2196F3", fg="white").pack(side=TOP, pady=10) output_text = Text(master, wrap=WORD) output_text.pack(side=TOP, fill=BOTH, expand=True, padx=10, pady=10) mainloop()
可选优化
Netmiko连接设备为阻塞操作,直接在主线程运行会导致Tkinter界面无响应,可将命令执行逻辑放到子线程中运行,执行完成后通过after方法回调更新界面,提升使用体验。
内容的提问来源于stack exchange,提问作者Hassan Kidan
相关产品推荐
相关产品推荐

