使用python遠程登錄

最近要使用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


程序很簡單,登錄自己的機器,執行ls命令,然後輸出結果。


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

當然,這個程序只是pexpect的一個實例程序,簡單介紹的它的簡單用法,還不足以說明它t的強大。


參考資料:

python文檔:http://docs.python.org/library/telnetlib.html

IBM developerWorks: http://www.ibm.com/developerworks/cn/linux/l-cn-pexpect1/

   http://www.ibm.com/developerworks/cn/linux/l-cn-pexpect2/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章