一些背景故事,这个应用程序可以接触到45+设备,并通过Netmiko执行一些SSH命令。 这是两个 GUI 窗口。第一个询问您的用户名/PW 以及用户的特定输入。 提交后,会弹出另一个带有按钮的 GUI 窗口。 选中此选项时,将运行函数的命令。 我已经设置了一个GUI,使其非常用户友好,希望允许我们的帮助台使用它。
我已经让它工作了,但是完成与设备的 10 个 SSH 会话需要 45 分钟以上。 我开始研究一些多线程或多进程的方法,但一直无法让它们工作。
任何帮助将不胜感激,以获得多处理/线程以减少处理时间。 目标是同时运行 5 到 10 个 SSH 会话,以帮助限制等待应用程序的时间。 还可能在进程运行时阻止第二个 GUI 窗口冻结。
下面是需要 10 分钟才能完成的工作代码。 我从一个单独的 python 文件中导入"a_devices",仅供参考。
#!/usr/bin/env python3
import netmiko
import sys
import os
from netmiko import ConnectHandler
from tkinter import *
import tkinter
from tkinter import ttk
import threading
from multiprocessing import Process
from multiprocessing import Pool
import time
import getpass
from Dictionaries import *
from netmiko.ssh_exception import NetMikoTimeoutException, NetMikoAuthenticationException
from paramiko.ssh_exception import SSHException
from datetime import datetime
vpntermination = None
username = input('Username: ')
password = getpass.win_getpass(prompt='Password: ', stream=None)
# Sends outputs to Text widgets
class StdoutRedirector(object):
def __init__(self,text_widget):
self.text_space = text_widget
def write(self,string):
self.text_space.insert('end', string)
self.text_space.see('end')
class Input_Window_GUI():
def __init__(self, master):
self.master = master
master.wm_title("VPN Termination Application")
self.label = Label(master, text="User to be terminated:", font=24).grid(row=0, column=2, columnspan=2)
self.master.geometry("650x600")
self.master.lift()
self.master.attributes('-topmost',True)
self.master.after_idle(master.attributes,'-topmost',False)
self.master.grid_columnconfigure(3, minsize=250, weight=1)
self.textBoxFrame = tkinter.Frame(master)
self.textBoxFrame.grid(row=5, column=3, columnspan=1, sticky=E+W)
self.textbox=Text(self.textBoxFrame)
self.textbox.grid(row=5, column=3, sticky=W, pady=2)
sys.stdout = StdoutRedirector(self.textbox)
self.e1 = Entry(self.master)
self.e1.insert(10,"")
self.e1.grid(row=1, column=2, columnspan=2)
self.submitButtonFrame = tkinter.Frame(master)
self.addButtonFrame = tkinter.Frame(master)
self.clearButtonFrame = tkinter.Frame(master)
self.submitButtonFrame.grid(row=6, column=1, columnspan=1)
self.addButtonFrame.grid(row=2, column=3, columnspan=1)
self.clearButtonFrame.grid(row=2, column=4, columnspan=1)
self.buttonFrameClose = tkinter.Frame(master)
self.buttonFrameClose.grid(row=6, column=4)
self.submit_button = Button(self.submitButtonFrame, text='Submit Changes', command=self.Submit_Application, height = 3, width = 15).grid(row=2, column=1, sticky=W, pady=2)
self.add_user_button = Button(self.addButtonFrame, text='Add User for Termination', command=self.Add_User, height = 3, width = 25).grid(row=2, column=2, sticky=W, pady=2)
self.close_app_button = Button(self.buttonFrameClose, text='Close App', command=self.Close_All, height = 3, width = 15).grid(row=6, column=3, sticky=E, pady=2)
self.clear_user_button = Button(self.clearButtonFrame, text='Clear All', command=self.Clear_User, height = 3, width = 15).grid(row=2, column=3, sticky=W, pady=2)
def Add_User(self):
try:
if not self.e1.get():# empty! (empty string is false value)
print('Ooops, nothing entered, please enter an acceptible username.')
elif self.e1.get() == " ":
print('Ooops, nothing entered, please enter an acceptible username.')
e1.delete(0,END)
else:
user = self.e1.get()
global vpntermination #Had to change to global so it could be passed throughout the multiple windows.
vpntermination = user
print("User staged for Termination: %s" % (user))
print("")
self.e1.delete(0,END)
return vpntermination
except ValueError:
print('Incorrect entry, please reenter username.')
self.e1.delete(0,END)
return 'Value'
except TypeError:
print('Incorrect entry, please reenter username.')
self.e1.delete(0,END)
return 'Type'
def Clear_User(self):
vpntermination = None
print("User cleared, readd User.")
print("")
def Close_All(self):
self.master.destroy()
sys.exit(1)
#Closes initial tkinter window and continues the code.
def Submit_Application(self):
self.master.after(1000, lambda: self.master.destroy())
class Output_Window_GUI:
def __init__(self, root):
self.root = root
root.wm_title("VPN Termination Output")
self.label = Label(root, text="Output:", font=24).grid(row=0, column=2, columnspan=2)
self.root.geometry("650x600")
self.root.lift()
self.root.attributes('-topmost',True)
self.root.after_idle(root.attributes,'-topmost',False)
self.textBoxFrame = tkinter.Frame(root)
self.textBoxFrame.grid(row=5, column=3, columnspan=1, sticky=E+W)
self.textbox=Text(self.textBoxFrame)
self.textbox.grid(row=5, column=3, sticky=W, pady=2)
#Calls the class to send CLI output to Textbox
sys.stdout = StdoutRedirector(self.textbox)
self.buttonFrameClose = tkinter.Frame(root)
self.buttonFrameClose.grid(row=6, column=3)
self.buttonFrame = tkinter.Frame(root)
self.buttonFrame.grid(row=2, column=2, columnspan=3)
self.close_all_button = Button(self.buttonFrameClose, text='Close App', command=self.Close_All, height = 3, width = 15).grid(row=2, column=1, sticky=W, pady=4)
self.start_button = Button(self.buttonFrame, text='Send Commands', command=self.Start_Commands, height = 3, width = 15).grid(row=2, column=1, sticky=W, pady=4)
def task():
root.after(2000, task)
def Close_All(self):
self.root.destroy()
sys.exit(1)
def Start_Commands(self):
print('VPN Termination Commands are in process for User: ' + vpntermination +'....please wait.')
print('')
start_time = datetime.now()
for a_device in all_firewalls:
per_fw_start_time = datetime.now()
try:
net_connect = ConnectHandler(**a_device)
hostname = net_connect.send_command("show hostname") #Used to store Hostname.
output = net_connect.send_command("vpn-sessiondb logoff name " + str(vpntermination) + " noconfirm") #Used for vpn termination command.
print('n******* Output for device ' + hostname + ' *******' )
print(output)
print('')
per_fw_end_time = datetime.now()
per_fw_total_time = per_fw_end_time - per_fw_start_time
print("******* " + hostname + " {0} *******".format(a_device['ip'])+ " took " + str(per_fw_total_time) + " to process.")
print('')
net_connect.disconnect() #Hoping to speed up process time within multi-threading issues.
except (NetMikoTimeoutException, NetMikoAuthenticationException) as e: #Handles timeout errors.
print("Could not connect to {}, due to {}", e)
print('')
end_time = datetime.now()
total_time = end_time - start_time
print('nTotal process time: ' + str(total_time))
def main():
#tkinter GUI that adds user for termination.
master = Tk()
my_gui = Input_Window_GUI(master)
master.mainloop()
#tkinter GUI that starts the user being terminated on all devices.
root=Tk()
out_gui = Output_Window_GUI(root)
root.mainloop()
if __name__ == '__main__':
main()
您可以做的是在运行mainloop
之前使用multiprocessing.Popen
创建一个multiprocessing.Queue
作为全局变量和一个单独的进程。
您在Popen
中使用的函数(在单独的进程中运行)应等待Queue
上的消息并对其执行操作。这个过程做了真正的工作。
同时,GUI 根据用户输入将命令(例如命令和用户名的 2 元组,如('delete', 'foo@bar')
)馈送到Queue
中。它还应使用after
回调来查询队列并处理来自其他进程的任何响应。
关于风格的一些说明。
- 在 Python 中,通常以大写字母开头的类名。函数和方法名称应为小写。参见 PEP8。
- 由于您运行的是 GUI,因此最好使用消息框来通知用户错误,而不是打印语句。根据操作系统和程序的启动方式,用户可能会也可能看不到打印的输出。
- 使用
from <module> import *
通常不被认为是好的做法。在这种情况下,我建议import tkinter as tk
.
好的,所以多亏了一些在线文章和罗兰史密斯,我才能让处理工作。 不幸的是,为了让它与 tkinter 一起工作,我不得不删除为用户发送函数的按钮,让它在 GUI 之间自动执行它。
目前用户名/密码没有通过,我知道要让它们通过,我可能需要将它们放在我循环的 Process args 部分中,以便将它们传递给每个进程(我还没有测试过)。
我可以使用更多的方向来让队列在我的 for 循环中站起来,并将进程中发生的任何事情传递给我的最终输出 GUI(root)。
def start_commands(vpntermination, a_device):
print('VPN Termination Commands are in process for User: ' + str(vpntermination) +'....please wait.')
print('')
start_time = datetime.now()
for a_device in all_firewalls: #Maybe add threading/processing into the for loop?
per_fw_start_time = datetime.now()
try:
net_connect = ConnectHandler(**a_device)
hostname = net_connect.send_command("show hostname") #Used to store Hostname.
output = net_connect.send_command("vpn-sessiondb logoff name " + str(vpntermination) + " noconfirm") #Used for vpn termination command.
print('n******* Output for device ' + hostname + ' *******' )
print(output)
print('')
per_fw_end_time = datetime.now()
per_fw_total_time = per_fw_end_time - per_fw_start_time
print("******* " + hostname + " {0} *******".format(a_device['ip'])+ " took " + str(per_fw_total_time) + " to process.")
print('')
net_connect.disconnect() #Hoping to speed up process time within multi-threading issues.
except (NetMikoTimeoutException, NetMikoAuthenticationException) as e: #Handles timeout errors.
print("Could not connect to {}, due to {}", e)
print('')
net_connect.disconnect() # Disconnect session if exception is thrown
end_time = datetime.now()
total_time = end_time - start_time
print('nTotal process time: ' + str(total_time))
def main():
username = input('Username: ')
password = getpass.win_getpass(prompt='Password: ', stream=None)
#tkinter GUI that adds user for termination.
master = Tk()
my_gui = InputWindowGUI(master)
master.mainloop()
#Move the loops below root tkinter and reenable the stdredirector.
procs = []
for a_device in all_firewalls:
print(a_device)
print(vpntermination)
my_proc = Process(target=start_commands, args=(a_device, vpntermination))
my_proc.start()
procs.append(my_proc)
for a_proc in procs:
print (a_proc)
a_proc.join()
#tkinter GUI that starts the user being terminated on all VCs.
root=Tk()
out_gui = OutputWindowGUI(root)
root.mainloop()
if __name__ == '__main__':
main()