Guest User

Untitled

a guest
Aug 21st, 2018
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.13 KB | None | 0 0
  1. How to implement a thread in a wxPython GUI application
  2. #!c:python27
  3.  
  4. import wx
  5. import os
  6. import re
  7. import paramiko
  8. import string
  9. import fileinput
  10. import os.path
  11. import dircache
  12. import sys
  13. import time
  14. import datetime, time
  15. import wx
  16.  
  17. from wxGui import *
  18.  
  19.  
  20.  
  21. class MyApp(wx.App):
  22. def OnInit(self):
  23. frame = MyFrame("SecureTool v2.0.0", (50, 60), (458, 332))
  24. frame.Show()
  25. self.SetTopWindow(frame)
  26. return True
  27.  
  28.  
  29.  
  30. class MyFrame(wx.Frame):
  31. def __init__(self, title, pos, size):
  32. wx.Frame.__init__(self, None, -1, title, pos, size)
  33.  
  34. toolbar = self.CreateToolBar()
  35. toolbar.Realize()
  36. menuFile = wx.Menu()
  37. menuFile.Append(1, "&About...")
  38. menuFile.AppendSeparator()
  39. menuFile.Append(2, "E&xit")
  40. menuBar = wx.MenuBar()
  41. menuBar.Append(menuFile, "&File")
  42. menu2 = wx.Menu()
  43. menu2.Append(wx.NewId(), "&Copy", "Copy in status bar")
  44. menu2.AppendSeparator()
  45. menu2.Append(wx.NewId(), "C&ut", "")
  46. menu2.AppendSeparator()
  47. menu2.Append(wx.NewId(), "Paste", "")
  48. menu2.AppendSeparator()
  49. menu2.Append(wx.NewId(), "&Options...", "Display Options")
  50. menuBar.Append(menu2, "&Edit")
  51.  
  52. self.SetMenuBar(menuBar)
  53. self.CreateStatusBar()
  54. self.SetStatusText("Welcome to SecureTool!")
  55. self.Bind(wx.EVT_MENU, self.OnAbout, id=1)
  56. self.Bind(wx.EVT_MENU, self.OnQuit, id=2)
  57. panel = wx.Panel(self)
  58. panel.SetBackgroundColour('LIGHT GREY')
  59. #Close button
  60. button = wx.Button(panel, label="EXIT", pos=(229, 160), size=(229, 80))
  61. self.Bind(wx.EVT_BUTTON, self.OnQuit, button)
  62. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  63. #Embed Server button
  64. button2 = wx.Button(panel, label="Embed Server", pos=(0, 160), size=(229, 80))
  65. self.Bind(wx.EVT_BUTTON, self.OnIP, button2)
  66. #Site Server
  67. button3 = wx.Button(panel, label="SITESERVER", pos=(0, 80), size=(229, 80))
  68. self.Bind(wx.EVT_BUTTON, self.OnUsrPswd, button3)
  69. #Local Search
  70. button4 = wx.Button(panel, label="LOCAL SEARCH", pos=(229, 80), size=(229, 80))
  71. self.Bind(wx.EVT_BUTTON, self.OnOpen, button4)
  72.  
  73. EVT_RESULT(self, self.OnResult)
  74. self.worker = None
  75.  
  76. def OnIP(self, event):
  77. ip_address = 0
  78. result = ''
  79. dlg = wx.TextEntryDialog(None, "Enter the IP Address.",
  80. 'Embed Server Connect', 'xxx.xxx.xxx.xxx')
  81. if dlg.ShowModal() == wx.ID_OK:
  82. ip_address = dlg.GetValue()
  83. if ip_address:
  84. cmsg = wx.MessageDialog(None, 'Do you want to connect to: ' + ip_address,
  85. 'Connect', wx.YES_NO | wx.ICON_QUESTION)
  86. result = cmsg.ShowModal()
  87.  
  88. if result == wx.ID_YES:
  89. self.DispConnect(ip_address)
  90.  
  91. cmsg.Destroy()
  92. dlg.Destroy()
  93. return True
  94.  
  95. def OnUsrPswd(self, event):
  96. passwrd = 0
  97. result = ''
  98. result = wx.TextEntryDialog(None, 'Enter Weekly Password', 'Site Server login','')
  99. if result.ShowModal() == wx.ID_OK:
  100. passwrd = result.GetValue()
  101. if passwrd:
  102. psmsg = wx.MessageDialog(None, 'Do you want to connect to the Siteserver?', 'Connect',
  103. wx.YES_NO | wx.ICON_QUESTION)
  104. result = psmsg.ShowModal()
  105. if result == wx.ID_YES:
  106. self.SiteserverConnect(passwrd)
  107.  
  108. psmsg.Destroy()
  109. result.Destroy()
  110. return True
  111.  
  112. def ErrMsg(self):
  113. ermsg = wx.MessageDialog(None, 'Invalid Entry!', 'ConnectionDialog', wx.ICON_ERROR)
  114. ermsg.ShowModal()
  115. ermsg.Destroy()
  116.  
  117. def GoodConnect(self):
  118. gdcnt = wx.MessageDialog(None, 'You are connected!', 'ConnectionStatus', wx.ICON_INFORMATION)
  119. gdcnt.ShowModal()
  120. #if gdcnt.ShowModal() == wx.ID_OK:
  121. gdcnt.Destroy()
  122.  
  123. def OnFinish(self):
  124. finish = wx.MessageDialog(None, 'Job is finished!', 'WorkStatus', wx.ICON_INFORMATION)
  125. finish.ShowModal()
  126. finish.Destroy()
  127.  
  128.  
  129. def DispConnect(self, address):
  130. pattern = r"b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)b"
  131. port = 22
  132. user = 'root'
  133. password ='******'
  134. if re.match(pattern, address):
  135. ssh = paramiko.SSHClient()
  136. ssh.load_system_host_keys()
  137. ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  138. ssh.connect(address,port,user,password)
  139. Ssh = ssh
  140. self.GoodConnect()
  141. self.OnSearch(Ssh)
  142. else:
  143. self.ErrMsg()
  144.  
  145. def SiteserverConnect(self, password):
  146. port = 22
  147. user = 'root2'
  148. address = '10.5.48.2'
  149. if password:
  150. ssh = paramiko.SSHClient()
  151. ssh.load_system_host_keys()
  152. ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  153. ssh.connect(address,port,user,password)
  154. Ssh = ssh
  155. self.GoodConnect()
  156. self.OnSiteSearch(Ssh)
  157. else:
  158. self.ErrMsg()
  159.  
  160. def startWorker(self,a, b, c):
  161. self.button2.Disable()
  162. self.thread = Thread(target=self.LongRunningSearch)
  163. self.thread.start()
  164.  
  165. def OnSearch(self, sssh):
  166. self.startWorker(self.OnFinish, self.LongRunningSearch, wargs=[sssh])
  167. self.OnFinish()
  168.  
  169. def LongRunningSearch(sssh):
  170. ssh = sssh
  171. apath = '/'
  172. apattern = '"*.txt" -o -name "*.log"'
  173. rawcommand = 'find {path} -name "*.txt" -o -name "*.log"'
  174. command1 = rawcommand.format(path=apath, pattern=apattern)
  175. stdin, stdout, stderr = ssh.exec_command(command1)
  176. filelist = stdout.read().splitlines()
  177. ftp = ssh.open_sftp()
  178. for afile in filelist:
  179. (head, filename) = os.path.split(afile)
  180.  
  181. paths = '/dispenser_result.log'
  182. temp = ftp.file(paths, 'w')
  183. from time import strftime
  184. temp.write("{0:^75}".format("Company -Security Report" ) + strftime(" %Y-%m-%d %H:%M:%S") + "nn")
  185. ustring = wx.TextEntryDialog(None, 'Enter a search string below:', 'Search', 'String Name')
  186. if ustring.ShowModal() == wx.ID_OK:
  187. userstring = ustring.GetValue()
  188.  
  189. if userstring:
  190. userStrHEX = userstring.encode('hex')
  191. userStrASCII = ''.join(str(ord(char)) for char in userstring)
  192. regex = re.compile(r"(%s|%s|%s)" % ( re.escape( userstring ), re.escape( userStrHEX ), re.escape( userStrASCII )))
  193. else:
  194. sys.exit('You Must Enter A String!!!')
  195.  
  196. count = 0
  197. for afile in filelist:
  198. (head, filename) = os.path.split(afile)
  199. if afile.endswith(".log") or afile.endswith(".txt"):
  200. f=ftp.open(afile, 'r')
  201. for i, line in enumerate(f.readlines()):
  202. result = regex.search(line)
  203. if result:
  204. count += 1
  205. ln = str(i)
  206. pathname = os.path.join(afile)
  207. template = "nnLine: {0}nFile: {1}nString Type: {2}nn"
  208. output = template.format(ln, pathname, result.group())
  209. ftp.get(afile, 'c:\Extracted\' + filename)
  210. temp.write(output)
  211. break
  212. else:
  213. #print "No Match in: " + os.path.join(afile)
  214. temp.write("nNo Match in: " + os.path.join(afile))
  215. f.close()
  216.  
  217. for fnum in filelist:
  218. #print "nFiles Searched: ", len(filelist)
  219. #print "Files Matched: ", count
  220. num = len(filelist)
  221.  
  222. temp.write("nnFiles Searched:" + '%sn' % (num))
  223. temp.write("Files Matched:"+ '%sn' % (count))
  224. temp.write("Search String:"+ '%sn' % (userstring))
  225. break
  226. temp.close()
  227. defaultFolder = "DispenserLogResults"
  228. if not defaultFolder.endswith(':') and not os.path.exists('c:\Extracted\DispenserLogResults'):
  229. os.mkdir('c:\Extracted\DispenserLogResults')
  230. else:
  231. pass
  232. ftp.get(paths, 'c:\Extracted\DispenserLogResults\dispenser_result.log')
  233.  
  234. ftp.remove(paths)
  235.  
  236. re.purge()
  237. ftp.close()
  238. ssh.close()
  239.  
  240. def OnSiteSearch(self, sssh):
  241. ssh = sssh
  242. apath = '/var/log/apache2 /var/opt/smartmerch/log/'
  243. apattern = '"*.log"'
  244. rawcommand = 'find {path} -type f -name "*.log"'
  245. command1 = rawcommand.format(path=apath, pattern=apattern)
  246. stdin, stdout, stderr = ssh.exec_command(command1)
  247. filelist = stdout.read().splitlines()
  248. ftp = ssh.open_sftp()
  249. for afile in filelist:
  250. (head, filename) = os.path.split(afile)
  251.  
  252. paths = '/var/tmp/siteserver_result.log'
  253. temp = ftp.file(paths, 'w')
  254. from time import strftime
  255. temp.write("{0:^75}".format("Gilbarco - SQA Security Report" ) + strftime(" %Y-%m-%d %H:%M:%S") + "nn")
  256. temp.write("n{0:^75}".format("SiteServer Logs" ))
  257. ustring = wx.TextEntryDialog(None, 'Enter a search string below:', 'Search', 'String Name')
  258. if ustring.ShowModal() == wx.ID_OK:
  259. userstring = ustring.GetValue()
  260.  
  261. if userstring:
  262. userStrHEX = userstring.encode('hex')
  263. userStrASCII = ''.join(str(ord(char)) for char in userstring)
  264. regex = re.compile(r"(%s|%s|%s)" % ( re.escape( userstring ), re.escape( userStrHEX ), re.escape( userStrASCII )))
  265. else:
  266. sys.exit('You Must Enter A String!!!')
  267.  
  268. count = 0
  269. for afile in filelist:
  270. (head, filename) = os.path.split(afile)
  271. if afile.endswith(".log") or afile.endswith(".txt"):
  272. f=ftp.open(afile, 'r')
  273. for i, line in enumerate(f.readlines()):
  274. result = regex.search(line)
  275. if result:
  276. count += 1
  277. ln = str(i)
  278. pathname = os.path.join(afile)
  279. template = "nnLine: {0}nFile: {1}nString Type: {2}nn"
  280. output = template.format(ln, pathname, result.group())
  281. ftp.get(afile, 'c:\Extracted\' + filename)
  282. temp.write(output)
  283. break
  284. else:
  285. temp.write("nNo Match in: " + os.path.join(afile))
  286. f.close()
  287.  
  288. for fnum in filelist:
  289. num = len(filelist)
  290.  
  291. temp.write("nnFiles Searched:" + '%sn' % (num))
  292. temp.write("Files Matched:"+ '%sn' % (count))
  293. temp.write("Search String:"+ '%sn' % (userstring))
  294. break
  295. temp.close()
  296. defaultFolder = "SiteServerLogResults"
  297. if not defaultFolder.endswith(':') and not os.path.exists('c:\Extracted\SiteServerLogResults'):
  298. os.mkdir('c:\Extracted\SiteServerLogResults')
  299. else:
  300. pass
  301. ftp.get(paths, 'c:\Extracted\SiteServerLogResults\siteserver_result.log')
  302.  
  303. ftp.remove(paths)
  304.  
  305. re.purge()
  306. ftp.close()
  307. ssh.close()
  308. self.OnFinish()
  309.  
  310. def OnOpen(self,e):
  311. self.dirname = ''
  312. dlg = wx.FileDialog(self, "Choose a file", self.dirname, "", "*.*", wx.OPEN)
  313. if dlg.ShowModal() == wx.ID_OK:
  314. self.filename = dlg.GetFilename()
  315. self.dirname = dlg.GetDirectory()
  316. f = open(os.path.join(self.dirname, self.filename), 'r')
  317. self.control.SetValue(f.read())
  318. f.close()
  319. dlg.Destroy()
  320.  
  321. def OnQuit(self, event):
  322. self.Close(True)
  323.  
  324. def OnAbout(self, event):
  325. wx.MessageBox("This is sQAST v2.0.0",
  326. "About secureTool", wx.OK | wx.ICON_INFORMATION, self)
  327.  
  328.  
  329.  
  330. def OnCloseWindow(self, event):
  331. self.Destroy()
  332.  
  333. if __name__ == '__main__':
  334. app = MyApp(False)
  335. app.MainLoop()
  336.  
  337. Traceback (most recent call last):
  338. File "C:SQA_logwxGui.py", line 87, in OnIP
  339. self.DispConnect(ip_address)
  340. File "C:SQA_logwxGui.py", line 143, in DispConnect
  341. self.OnSearch(Ssh)
  342. File "C:SQA_logwxGui.py", line 169, in OnSearch
  343. self.startWorker(self.OnFinish, self.LongRunningSearch, wargs=[sssh])
  344.  
  345. def OnSearch(self, sssh):
  346. self.LongRunningSearch(sssh) # Move all the blocking code here,
  347. # just NOT the GUI reaction !
  348. # Meaning self.OnFinish()...
  349. self.OnFinish()
  350.  
  351. def OnSearch(self, sssh):
  352. startWorker(self.OnFinish, self.LongRunningSearch, wargs=[sssh])
  353.  
  354. from time import sleep
  355. import wx
  356. from wx.lib.delayedresult import startWorker
  357.  
  358. class MainWindow(wx.Frame):
  359. def __init__(self, *args, **kwargs):
  360. wx.Frame.__init__(self, *args, **kwargs)
  361.  
  362. self.panel = wx.Panel(self)
  363. self.startButton = wx.Button(self.panel, label="Long Task")
  364. self.abortButton = wx.Button(self.panel, label="Abort")
  365. self.abortButton.Disable()
  366. self.gauge = wx.Gauge(self.panel, size=(-1, 20))
  367. self.shouldAbort = False
  368.  
  369. self.startButton.Bind(wx.EVT_BUTTON, self.OnStartButton)
  370. self.abortButton.Bind(wx.EVT_BUTTON, self.OnAbortButton)
  371.  
  372. self.windowSizer = wx.BoxSizer()
  373. self.windowSizer.Add(self.panel, 1, wx.ALL | wx.EXPAND)
  374.  
  375. self.sizer = wx.BoxSizer(wx.VERTICAL)
  376. self.sizer.Add(self.startButton)
  377. self.sizer.Add(self.abortButton)
  378. self.sizer.Add((10, 10))
  379. self.sizer.Add(self.gauge)
  380.  
  381. self.border = wx.BoxSizer()
  382. self.border.Add(self.sizer, 1, wx.ALL | wx.EXPAND, 5)
  383.  
  384. self.panel.SetSizerAndFit(self.border)
  385. self.SetSizerAndFit(self.windowSizer)
  386. self.Show()
  387.  
  388. def OnStartButton(self, e):
  389. self.startButton.Disable()
  390. self.abortButton.Enable()
  391. startWorker(self.LongTaskDone, self.LongTask)
  392.  
  393. def OnAbortButton(self, e):
  394. self.shouldAbort = True
  395.  
  396. def LongTask(self):
  397. for a in range(101):
  398. sleep(0.05)
  399. wx.CallAfter(self.gauge.SetValue, a)
  400. if self.shouldAbort:
  401. break
  402. return self.shouldAbort
  403.  
  404. def LongTaskDone(self, result):
  405. r = result.get()
  406. if r:
  407. print("Aborted!")
  408. else:
  409. print("Ended!")
  410. self.startButton.Enable()
  411. self.abortButton.Disable()
  412. self.shouldAbort = False
  413. self.gauge.SetValue(0)
  414.  
  415. app = wx.App(False)
  416. win = MainWindow(None)
  417. app.MainLoop()
  418.  
  419. from time import sleep
  420. from threading import Thread
  421. import wx
  422.  
  423. class MainWindow(wx.Frame):
  424. def __init__(self, *args, **kwargs):
  425. wx.Frame.__init__(self, *args, **kwargs)
  426.  
  427. self.panel = wx.Panel(self)
  428. self.startButton = wx.Button(self.panel, label="Long Task")
  429. self.abortButton = wx.Button(self.panel, label="Abort")
  430. self.abortButton.Disable()
  431. self.gauge = wx.Gauge(self.panel, size=(-1, 20))
  432. self.shouldAbort = False
  433. self.thread = None
  434.  
  435. self.startButton.Bind(wx.EVT_BUTTON, self.OnStartButton)
  436. self.abortButton.Bind(wx.EVT_BUTTON, self.OnAbortButton)
  437.  
  438. self.windowSizer = wx.BoxSizer()
  439. self.windowSizer.Add(self.panel, 1, wx.ALL | wx.EXPAND)
  440.  
  441. self.sizer = wx.BoxSizer(wx.VERTICAL)
  442. self.sizer.Add(self.startButton)
  443. self.sizer.Add(self.abortButton)
  444. self.sizer.Add((10, 10))
  445. self.sizer.Add(self.gauge)
  446.  
  447. self.border = wx.BoxSizer()
  448. self.border.Add(self.sizer, 1, wx.ALL | wx.EXPAND, 5)
  449.  
  450. self.panel.SetSizerAndFit(self.border)
  451. self.SetSizerAndFit(self.windowSizer)
  452. self.Show()
  453.  
  454. def OnStartButton(self, e):
  455. self.startButton.Disable()
  456. self.abortButton.Enable()
  457. self.thread = Thread(target=self.LongTask)
  458. self.thread.start()
  459.  
  460. def OnAbortButton(self, e):
  461. self.shouldAbort = True
  462.  
  463. def LongTask(self):
  464. for a in range(101):
  465. sleep(0.05)
  466. wx.CallAfter(self.gauge.SetValue, a)
  467. if self.shouldAbort:
  468. break
  469. wx.CallAfter(self.LongTaskDone, self.shouldAbort)
  470.  
  471. def LongTaskDone(self, r):
  472. if r:
  473. print("Aborted!")
  474. else:
  475. print("Ended!")
  476. self.startButton.Enable()
  477. self.abortButton.Disable()
  478. self.shouldAbort = False
  479. self.gauge.SetValue(0)
  480.  
  481. app = wx.App(False)
  482. win = MainWindow(None)
  483. app.MainLoop()
Add Comment
Please, Sign In to add comment