Pythonでtelnet接続してみる(その2)
前回のPythonでtelnet接続してみるでPythonでtelent接続できることを確認した。結果が文字化けしていたが文字コード変換し、エスケープシーケンス文字列を除去できた。
でも、やっぱり必要な部分だけ表示できたほうが便利だ、ということで、ログインした直後のOSメッセージなどを除去してみることにした。
前回の結果をみれば一目瞭然だが、コマンドを発行したプロンプトから次ぎのプロンプト直前までを抽出すれば良さそうだ。telnetlibで得られた文字列を改行部分で分割し、それぞれの行からなるリストを処理する。
プログラム
# -*- coding: utf-8 -*-
import re
import telnetlib
HOST = "192.168.11.201" # your server
user = "bty" # your user name
password = "*****" # your password
tn = telnetlib.Telnet(HOST)
tn.read_until("login: ")
tn.write(user + "\n")
if password:
tn.read_until("Password: ")
tn.write(password + "\n")
tn.write("ls -al\n")
tn.write("exit\n")
result = tn.read_all()
#エスケープシーケンスの除去する
r = re.compile(r'\x1b\[.*?m\[?')
result1 = re.sub(r,'',result)
#結果の文字列を改行部分で分解し、各行からなるリストを取得する
#lines = result1.split('\r\n')
lines = result1.splitlines()
#プロンプトから次のプロンプト直前までの行を抽出する
prompt = "bty@ub01:~$" # your prompt
flg = None
lines2 = []
for line in lines:
if flg == None:
if prompt in line:
flg = True
else:
if prompt in line:
break;
lines2.append(line)
#文字コードutf-8をcp932に変換して表示する
for line in lines2:
print line.decode('utf-8').encode('cp932')
結果
合計 44 drwxr-xr-x 5 bty bty 4096 1月 16 22:00 . drwxr-xr-x 3 root root 4096 1月 16 16:24 .. -rw------- 1 bty bty 1998 5月 6 16:54 .bash_history -rw-r--r-- 1 bty bty 220 1月 16 16:24 .bash_logout -rw-r--r-- 1 bty bty 3574 1月 16 16:35 .bashrc drwx------ 2 bty bty 4096 1月 16 16:26 .cache drwx------ 3 bty bty 4096 5月 3 19:07 .emacs.d -rw------- 1 bty bty 35 1月 16 16:28 .lesshst -rw-r--r-- 1 bty bty 675 1月 16 16:24 .profile -rw------- 1 bty bty 3897 1月 16 22:00 .viminfo drwxrwxr-x 3 bty bty 4096 1月 16 17:48 my
参考
5. 組み込み型 — Python 2.7ja1 documentation
文字列メッソド str.split(), str.splitlines()
|
【送料無料】エキスパートPythonプログラミング [ タレク・ジアデ ] |
