Pythonでtelnet接続してみる-wxPython(その6)
Pythonでtelnet接続してみる-wxPython(その5)の実験では、表示する文字が小さく、等幅でないので見にくい。また、リモートホストから受信した文字列がワンテンポ遅れて表示される。なんとか、これらの不満を改善してみた。
●表示を見やすくする
フォントを等幅にするために"Terminal"を設定し、サイズを12ポイントにする
font = wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.NORMAL, False, "Terminal") self.dspText.SetFont(font)
●ワンテンポ遅れの表示を改善する
onConnectBtnメソッドでtelnet_ub01関数から文字列を受け取って表示させていたが、telnet_ub01関数内で表示させるようにする。厳密なリアルタイムじゃないけど、目的からすればこれでじゅうぶんだ。
1) onConnectBtnメソッドから telenet_ub01関数に self.dspTextオブジェクトを渡す。
def onConnectBtn(self, event):
telnet_ub01(self.dspText)
2) telnet_ub01関数の中で、WriteTextメソッドを呼び、文字列を表示する。
def telnet_ub01(p):
....
res = tn.connect()
p.WriteText(res)
....
プログラム
# -*- coding: utf-8 -*-
import wx
import re
import telnetlib
class MyTelnet(object):
def __init__(self, host, user, pswd, prompt):
self.host = host
self.user = user
self.pswd = pswd
self.prompt = prompt
def connect(self):
self.tn = telnetlib.Telnet(self.host)
self.tn.read_until("login: ")
self.tn.write(self.user + "\n")
self.tn.read_until("Password: ")
self.tn.write(self.pswd + "\n")
res = self.tn.read_until(self.prompt)
return self.cvtstr(res)
def action(self, cmd):
self.tn.write(cmd + "\n")
res = self.tn.read_until(self.prompt)
return self.cvtstr(res)
def disconnect(self):
self.tn.write("exit\n")
res = self.tn.read_all()
return self.cvtstr(res)
def cvtstr(self, s):
#エスケープシーケンスの除去
r = re.compile(r'\x1b\[.*?m\[?')
s = re.sub(r,'',s)
#文字コードutf-8をunicodeに変換
return s.decode('utf-8')
def telnet_ub01(p):
HOST = "192.168.11.201" # your server
USER = "bty" # your user name
PASSWORD = "*******" # your password
PROMPT = "bty@ub01:~$" # your prompt
tn = MyTelnet(HOST, USER, PASSWORD, PROMPT)
res = tn.connect()
p.WriteText(res)
res = tn.action("ls -al")
p.WriteText(res)
res = tn.action("df")
p.WriteText(res)
res = tn.disconnect()
p.WriteText(res)
class MyFrame(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, title=title, size=(600,400))
ctlPanel = wx.Panel(self)
connectBtn = wx.Button(ctlPanel, label=u"接続")
self.Bind(wx.EVT_BUTTON, self.onConnectBtn, connectBtn)
quitBtn = wx.Button(ctlPanel, label=u"終了")
self.Bind(wx.EVT_BUTTON, self.onQuitBtn, quitBtn)
ctlSz = wx.BoxSizer(wx.VERTICAL)
ctlSz.Add(connectBtn)
ctlSz.Add(quitBtn)
ctlPanel.SetSizer(ctlSz)
self.dspText = wx.TextCtrl(self, style=wx.TE_MULTILINE)
font = wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.NORMAL, False, "Terminal")
self.dspText.SetFont(font)
sz = wx.BoxSizer(wx.HORIZONTAL)
sz.Add(ctlPanel, 0, wx.EXPAND)
sz.Add(self.dspText, 1, wx.EXPAND)
self.SetSizer(sz)
self.Show(True)
def onConnectBtn(self, event):
telnet_ub01(self.dspText)
def onQuitBtn(self, event):
self.Close()
app = wx.App(False)
frame = MyFrame(None, 'MYTELNET')
app.MainLoop()

