PythonからCisco機器にTelnet接続してみました ~その1~
Cisco Aironet に MACアドレスを登録する処理を半自動化してみたく、Pythonを使ってみました。
まずは Python で Telnet接続し、簡単なCiscoコマンドを発行してみます。
実装環境
Pythonのバージョンは 3.6.1を使用
Ciscoのプロンプトは通常下記。
User Access Verification Password:
import getpass import telnetlib HOST = '192.168.xxx.xxx' password = getpass.getpass() tn = telnetlib.Telnet(HOST) if password: tn.read_until(b'Password: ') tn.write(password.encode('ascii') + b'\n') # Ciscoコマンド発行 tn.write(b'show clock' + b'\n') tn.write(b'exit' + b'\n') # read_until以降のテキストを出力 print(tn.read_all().decode('ascii'))
実行結果は以下の通り。
Password: <手入力> router>show clock Load for five secs: 0%/0%; one minute: 0%; five minutes: 0% Time source is SNTP, 18:55:19.232 JST Tue Jun 27 2017 18:55:19.232 JST Tue Jun 27 2017 router>exit