Pythonでtelnet接続してみる(その3)
前回のPythonでtelnet接続してみる(その2)で、コマンド実行結果を切り出して表示させたのだが、そんな厳密なことをやらなくてもいいんじゃないか、と思い始めた。
Telnet.read_until(expected[, timeout])
expected で指定された文字列を読み込むか、 timeout で指定された秒数が経過するまで読み込みます。
与えられた文字列に一致する部分が見つからなかった場合、読み込むことができたもの全てを返します。これは空の文字列になる可能性があります。接続が閉じられ、転送処理済みのデータが得られない場合には EOFError が送出されます。
read_until メソッドは、リモートホストから受信した文字列を読み込み、指定した文字列にマッチしたら、それまでに読んだ文字列をすべて返す。したがって、その部分が必要がなければ表示させなければ良いだけだ。
それから、リモートで接続しているので、現在の接続状況がどうなっているのか、ある程度わかるようにしておいたほうが良いと思う。
プログラム
# -*- coding: utf-8 -*-
import re
import telnetlib
HOST = "192.168.11.201" # your server
USER = "bty" # your user name
PASSWORD = "*******" # your password
PROMPT = "bty@ub01:~$" # your prompt
def print_tn(s):
#エスケープシーケンスの除去
r = re.compile(r'\x1b\[.*?m\[?')
s = re.sub(r,'',s)
#文字コードutf-8をcp932に変換して表示する
print s.decode('utf-8').encode('cp932'),
tn = telnetlib.Telnet(HOST)
tn.read_until("login: ")
tn.write(USER + "\n")
tn.read_until("Password: ")
tn.write(PASSWORD + "\n")
tn.read_until(PROMPT)
tn.write("ls -al\n")
res = tn.read_until(PROMPT)
print_tn(res)
tn.write("exit\n")
res = tn.read_all()
print_tn(res)
実行結果
ls -al 合計 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 2501 5月 11 11:35 .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 bty@ub01:~$ exit ログアウト
参考
20.14. telnetlib — Telnet クライアント — Python 2.7ja1 documentation
