最近要使用python做一个在web上管理交换机的程序,需要远程登录,就查了点资料,由于还没有搞到交换机,就先用自己的机器测试一下。
首先python的标准库中包含telnet,用起来也很方便,查看一下文档写了个小程序:
#!/usr/bin/env python
#coding=utf-8
import telnetlib
host = "127.0.0.1"
userName = 'root'
password = '123456'
enter = '\n'
t = telnetlib.Telnet(host)
t.read_until("login: ",1)
t.write(userName + enter)
t.read_until("Password: ",1)
t.write(password + enter)
t.write("ls"+enter)
t.write("exit"+enter)
print t.read_all()
输出结果:
Last login: Wed Nov 2 14:51:36 on console
shi-kefumatoiMac:~ root# .CFUserTextEncoding .subversion Library
.forward .viminfo nat.sh
.sh_history .vimrc noc
shi-kefumatoiMac:~ root# logout