telnetlibのTelnetでコマンド実行結果だけを取得する。

Pythonの標準ライブラリであるtelnetlibを使用する時に特定のコマンドの実行結果のみが欲しかったので試してみました。read_until()だけでは実行コマンドやその後のプロンプトを読み飛ばす事が難しかったので、"ゴミ\n欲しい結果\nゴミ"という形で取得してスライシングで'欲しい結果'のみを抽出しています。

ソースコード

# -*- coding:utf-8 -*-
import getpass
import sys
import telnetlib

HOST = "192.168.1.13"
user = raw_input("Enter your remote account: ")
password = getpass.getpass()

tn = telnetlib.Telnet(HOST)

tn.read_until("login: ")
tn.write(user + "\n")
if password:
    tn.read_until("Password: ")
    tn.write(password + "\n")

tn.read_until('~$ ') # コマンドを実行する直前まで読み飛ばす
tn.write("ls\n")
result = tn.read_until('~$ ') # lsコマンド結果とゴミを格納
tn.write("exit\n")

tL = result.split("\n")[1:-1] # コマンドとプロンプトを削除
for line in tL:
    print line

実行結果

目的であるlsコマンドの実行結果だけを取得する事ができました。

macbook:~ ox$ python fuga.py 
Enter your remote account:  ox 
Password: 
Desktop    Downloads  Music     Public     Videos
Documents  Examples   Pictures  Templates

real_all()で取得すると?

Python標準ライブラリのサンプルのようにread_all()を使用して結果を取得した場合、allの名前の通り、最後に実行したread_until()からEOFまで全て取得されてしまいます。この状態から切り出すのは面倒くさいので、read_until()をうまく利用してできるだけゴミを減らすといいと思います。

ソース

import getpass
import sys
import telnetlib

HOST = "192.168.1.13"
user = raw_input("Enter your remote account: ")
password = getpass.getpass()

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\n")
tn.write("exit\n")

print tn.read_all()

実行結果

macbook:~ ox$ python hoge.py 
Enter your remote account: ox
Password: 

Last login: Mon Jul  4 22:42:15 JST 2011 from 192.168.1.10 on pts/2
ls
exit
Linux ubuntu-vm 2.6.32-32-generic #62-Ubuntu SMP Wed Apr 20 21:54:21 UTC 2011 i686 GNU/Linux
Ubuntu 10.04.2 LTS

Welcome to Ubuntu!
 * Documentation:  https://help.ubuntu.com/

  System information as of Mon Jul  4 22:42:26 JST 2011

  System load:  0.14               Processes:           139
  Usage of /:   25.6% of 18.97GB   Users logged in:     1
  Memory usage: 44%                IP address for eth1: 192.168.1.13
  Swap usage:   0%

  Graph this data and manage this system at https://landscape.canonical.com/

0 packages can be updated.
0 updates are security updates.

ox@ubuntu-vm:~$ ls
Desktop    Downloads  Music     Public     Videos
Documents  Examples   Pictures  Templates
ox@ubuntu-vm:~$ exit
logout