下面是我的程序使用Paramiko连接到Ubuntu服务器的五个功能。我用Python编写了一个命令行脚本,可以完美地处理这个问题,但是我正在尝试学习wxPython,并且遇到了一些挑战。如果我有一个函数,脚本工作得很好,但是,作为一个新手,我正在努力练习编写更有效的代码。正如函数一样,我得到一条消息,"ssh未定义…"我试过传递参数和其他组合的东西……我想我忽略了什么。有人能帮我一下吗?
def OnIP(self, event):
panel=wx.Panel(self)
dlg = wx.TextEntryDialog(None, "Enter the IP Address.",
'Dispenser Connect', 'xxx.xxx.xxx.xxx')
if dlg.ShowModal() == wx.ID_OK:
ip_address = dlg.GetValue()
if ip_address:
cmsg = wx.MessageDialog(None, 'Do you want to connect to: ' + ip_address,
'Connect', wx.YES_NO | wx.ICON_QUESTION)
result = cmsg.ShowModal()
if result == wx.ID_YES:
self.DispConnect(ip_address)
cmsg.Destroy()
dlg.Destroy()
return True
def GoodConnect(self):
gdcnt = wx.MessageDialog(None, 'You are connected!', 'ConnectionStatus', wx.ICON_INFORMATION)
gdcnt.ShowModal()
if gdcnt.ShowModal() == wx.ID_OK:
self.OnSearch()
gdcnt.Destroy()
def ErrMsg(self):
ermsg = wx.MessageDialog(None, 'Invalid Entry!', 'ConnectionDialog', wx.ICON_ERROR)
ermsg.ShowModal()
ermsg.Destroy()
def DispConnect(self, address):
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"
port = 22
user = 'root'
password ='******'
if re.match(pattern, address):
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(address,port,user,password)
self.GoodConnect()
else:
self.ErrMsg()
def OnSearch(self, somevariable):
apath = '/'
apattern = '"*.txt" -o -name "*.log"'
rawcommand = 'find {path} -name "*.txt" -o -name "*.log"' #{pattern}
command1 = rawcommand.format(path=apath, pattern=apattern)
stdin, stdout, stderr = ssh.exec_command(command1)
filelist = stdout.read().splitlines()
ftp = ssh.open_sftp()
您在DispConnect()
中定义了ssh
,但随后在OnSearch()
中再次使用它,其中它尚未定义。由于这些都发生在同一个类中(我假设),因此将if re.match...
中的最后一行设置为
self.ssh = ssh
然后在OnSearch()中,使用self.ssh
而不是ssh
。
也就是说,在方法中使用的局部变量在这些方法之外不可用。使用self.ssh
使其成为类的成员,然后它可以在类中的任何地方使用。