发布时间:2019-09-13 09:25:16编辑:auto阅读(1850)
最近要使用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
telnet很好用,但是总是有人喜欢更强大更好用的程序,于是就有了pexpect,pexpect 是 Don Libes 的 Expect 语言的一个 Python 实现,是一个用来启动子程序,并使用正则表达式对程序输出做出特定响应,以此实现与其自动交互的 Python 模块。 Pexpect 的使用范围很广,可以用来实现与 ssh、ftp 、telnet 等程序的自动交互;可以用来自动复制软件安装包并在不同机器自动安装;还可以用来实现软件测试中与命令行交互的自动化。
看了写资料,也用pexpect写了一个小程序,实现刚才同样的功能:
#!/usr/bin/env python
#coding=utf-8
import pexpect
address = '127.0.0.1'
userName = 'root'
password = '123456'
cmd = 'telnet ' + address
prompt = '[$#>]'
child = pexpect.spawn(cmd)
index = child.expect(['login',pexpect.EOF,pexpect.TIMEOUT],timeout=1)
if index == 0:
child.sendline(userName)
index = child.expect('Password',timeout=1)
child.sendline(password)
child.expect(prompt,timeout=1)
child.sendline('ls')
child.expect('ls',timeout=1)
child.expect(prompt,timeout=1)
print child.before
else:
print 'expect "login",but get EOF or TIMEOUT'
child.close()
输出结果:
.CFUserTextEncoding .subversion Library
.forward .viminfo nat.sh
.sh_history .vimrc noc
shi-kefumatoiMac:~ root
python文档:http://docs.python.org/library/telnetlib.html
IBM developerWorks: http://www.ibm.com/developerworks/cn/linux/l-cn-pexpect1/
上一篇: python中mat()函数
下一篇: Python utc转化时间
48731
47767
38543
35738
30173
26913
25943
20785
20553
18941
332°
408°
442°
463°
448°
439°
492°
564°
679°
692°