Pythonでtelnet接続してみる-wxPython(その5)
やっぱり、Windowsで動かすアプリはGUIじゃないと格好つかない。
ということで、wxPython で GUIプログラムの実験をしてみた。
wxPython では、ベースとなる Frame に、ボタンを配置するための ctlPanel と、リモートホストから受信した文字列を表示するための dspText を作る。
ctlPanelに表示するボタンは、telnet接続してコマンド実行するための「接続」ボタン、アプリを終了するための「終了」ボタンを作った。BoxSizerで垂直方向(VERTICAL)に並べる。
そして、ボタンを配置したctlPanel と、dspText を BoxSizer で水平方向(HORIZONTAL)にならべて画面を作った。
「接続」ボタンをクリックすると、Bindメソッドで紐づけられた onConnectBtnメソッドが呼ばれ、telnet接続する telnet_ub01関数を実行してリモートホストからの文字列が返る。dspText の WriteTextメソッドで文字列を表示させる。
WriteTextメソッドで渡す文字列の文字コードはunicodeでなければならない。なので、MyTelnet クラスで、cvtstrメソッドの文字コード変換部分を utf-8 から unicode への変換としている。
実行してみると、telent接続、コマンド実行の一連の処理が終了してから、結果が表示されるので、反応がのろい感じがしてしまう。接続、コマンド実行の単位で結果表示するようにしないと、アプリが動作しているのかどうか不安になる。
いろいろ問題があるにせよ、こんな簡単なスクリプトで、Windows GUIアプリが作れてしまう。
プログラム
# -*- 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():
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()
res += tn.action("ls -al")
res += tn.action("df")
res += tn.disconnect()
return 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)
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):
result = telnet_ub01()
self.dspText.WriteText(result)
def onQuitBtn(self, event):
self.Close()
app = wx.App(False)
frame = MyFrame(None, 'MYTELNET')
app.MainLoop()

