连接到SSH后弹出消息框

时间:2013-06-25 05:05:31

标签: python ssh wxpython messagebox

大家好我正在学习Python并使用wxPython制作GUI模型。

我想连接vai SSH,我为此目的使用了pexpect。我想显示一个msg框,说“连接到服务器”或者如果断开连接,“连接未建立” 我无法弄清楚如何做到这一点,GUI连接时会冻结。如何避免冻结GUI? 我的示例代码是:

import time
import sys
import pexpect
c = pexpect.spawn("ssh -Y -L xxxx:localhost:xxxx user @ host.com")
#time.sleep(0.1)
c.expect("[pP]aasword")
c.sendline("xxxxxx")
#time.sleep(0.2)
c.interact()
c.pexpect([user@host.com~]$)

在此处连接到SSH后,GUI冻结。连接后,我想在消息框中显示连接状态,而不是在终端中。请建议怎么做;作为初学者,我觉得很难。

提前致谢。

更新

import wx
import os
import pexpect
import sys
import subprocess
import time
class Connect_ssh(wx.Frame):
    def __init__ (self, *args, **kw):
        wx.Frame.__init__(self,None,wx.ID_ANY,"Secure Shell",    size=(310,200),style=wx.DEFAULT_FRAME_STYLE ^ wx.MAXIMIZE_BOX ^ wx.RESIZE_BORDER)
        panel = wx.Panel(self)
        txt1 = wx.StaticText(panel, label="Account name:",pos=(20, 55))
        txt2 = wx.StaticText(panel, label="Password",pos=(20, 105))
        self.txt_name = wx.TextCtrl(panel, -1, size=(130, -1), pos=(160,50))
        self.txt_pswd= wx.TextCtrl(panel, -1, size=(130, -1),pos= (160,100),style=wx.TE_PASSWORD)
        button1 = wx.Button(panel, -1, "Connect",size=(-1,-1), pos=(50, 160))
        button2 = wx.Button(panel, -1, "Disconnect",size=(-1,-1), pos=(170, 160))
        self.Bind(wx.EVT_BUTTON,self.OnConc,button1)
   def OnConc(self,event):
        u_name = self.txt_name.GetValue()
        passwd = self.txt_pswd.GetValue()
        child = pexpect.spawn("ssh -Y -L xxx:localhost:xxx %s@host.com" % (str(u_name)))
        child.expect("%s@host.com's password:" % (str(u_name)) )
        child.sendline("%s" % (str(passwd)))
        child.interact()
        #child.sendline("%s" % str(sub))
        child.expect("[%s@qvislabs.com~]$"% (str(u_name)) )
        #time.sleep()
        #self.Destroy()
        msg = wx.MessageBOx(" '%s'@host.com is connected" % (str(u_name)), "Info",wx_OK)
        self.Hide()

if __name__=="__main__":
app = wx.App()
Connect_ssh().Show()
app.MainLoop()

1 个答案:

答案 0 :(得分:1)

GUI可能正在冻结,因为SSH连接阻止了主循环。要解决此问题,您必须将连接代码放入单独的线程中。然后使用wxPython的线程安全方法之一(wx.CallAfter,wx.CallLater或wx.PostEvent)告诉GUI显示弹出对话框。

有关wxPython和线程的信息,请参阅以下链接: