Python Pexpect庫的簡單使用
Python Pexpect庫的使用
簡介
最近需要遠端操作一個伺服器並執行該伺服器上的一個python指令碼,查到可以使用Pexpect這個庫。記錄一下。
什麼是Pexpect?Pexpect能夠產生子應用程式,並控制他們,並能夠通過期望模式對子應用的輸出做出反應。Pexpect允許你的指令碼產生子應用、控制他們像一個人類在輸入命令一樣。
Pexpect使用在自動互動的應用,例如SSH、SFTP、PASSWD、TELNET。它可以被應用在使用自動設定指令碼為不同的伺服器自動地重複的安裝軟體包。也可以被應用在自動的軟體測試。
Pexpect的主要特點是需要Python的基本庫pty,這個庫只有在類Unix系統上才有
Pexpect關於SSH的使用
注:測試,我們直接用虛擬機器本機ssh本機
- 環境
1. win10 物理機 2. Vmware Centos 虛擬機器 3. Xshell 4. 虛擬機器python安裝pexpect:pip install pexpect
- 在虛擬機器建立一個 python檔案
#-*- coding:UTF-8 -*- import pexpect # 定義ssh連線 def ssh(user,host,password,command): #建立子應用,命令是 ssh -l root 127.0.0.1 python /home/python/test.py child = pexpect.spawn('ssh -l %s %s %s'%(user,host,command)) # 期待開啟的子程式的顯示,子程式的不同顯示會匹配到不同key然後我們定義不同的操作 # 0 : 連線超時 # 1 :ssh有時候提示你是否確認連線 # 2 :提示輸入密碼 # 3 :匹配到#號,表示命令已經執行完畢。沒用到 i = child.expect([pexpect.TIMEOUT, 'Are you sure you want to continue connecting','password:',r"([^-]>|#)"]) # 如果登入超時,renturn none if i == 0: # Timeout print "Timeout" return None # 提示是否確認連線 if i == 1: child.sendline ('yes')# 我們輸入yes child.expect ('password: ')# 輸入yes後 子程式應該提示輸入密碼,我們再次期待password i = child.expect([pexpect.TIMEOUT, 'password: ']) #超時 if i == 0: # Timeout return None # 不考慮其他情況,走到此處時,要麼timeout 已經return ,要麼等待輸入密碼 #輸入密碼 child.sendline(password) # 返回子程式 return child if __name__ =='__main__': try: # 配置資料 host='127.0.0.1' user="root" password = '********' command = 'python /home/python/test.py' #command="ls -l" child = ssh(user,host,password,command) #這句是將子程式的命令列拉到末端 test = child.expect(pexpect.EOF) #child中before就是我們要的資料,有時候還會在 after中 print child.before print child.after except Exception,e: print str(e) # 最終的顯示結果是 test.py中列印的hahaha結果, [root@localhost python]# python test_pexpect.py hahaha <class 'pexpect.exceptions.EOF'>
- 我們嘗試一下開兩個虛擬機器的情況
上面的程式碼只需要更改ip user password即可 # ip 192.168.233.133 # user root # 在另一臺虛擬機器的相同位置建立/home/pyhton/test.py 內容如下 if __name__=="__main__": print "another virual machine hahaha" # 列印結果 [root@localhost python]# python test3.py another virual machine hahaha <class 'pexpect.exceptions.EOF'>
Pexpect 關於 SFTP的使用
與ssh相同,就是使用python在當前機器上輸入sftp ip 然後期望結果,輸入密碼,併發送get下載檔案即可。
注:使用的時候發現一點注意:在每次執行sendline之前 都需要重新期望一下當前的sftp>,或者在每次輸入sendline之後重新期望一下sftp>。也就是期望到這行,否則輸入的命令都沒有反應,我理解是遠端連線的伺服器有輸出時候當前的位置可能不在sftp>這裡所以在sendline的任何東西都是無意義的。如果這個解釋不對望高人指點一下,
# --*-- coding:utf-8 --*-- import pexpect import os import time def sftp(ip , password , command): # 建立子應用 child = pexpect.spawn("sftp %s"%(ip)) i = child.expect([pexpect.TIMEOUT,'password:']) # 超時 if i == 0 : print "Timeout" return None # 準備輸入密碼 if i == 1 : # 輸入密碼 child.sendline(password) j = child.expect([pexpect.TIMEOUT,'sftp>']) # 超時 if j == 0: print "Timeout" return None # 匹配到進入sftp命令模式 if j==1: print 'Before sftp get command' print child.before print "-----------------" #傳送命令 child.sendline(command) child.expect(['sftp>']) print "After sftp get command" print child.before print "-----------------" child.sendline("bye") #child.expect(['sftp>']) print "After sftp bye" print child.before print "-----------------" print child.after return child if __name__=='__main__': ip = "192.168.233.133" command = "get /home/python/test.txt" password = "********" child = sftp(ip , password , command) print child.before print child.after if os.path.exists("./test.txt"): print "Make sure transfer successfully" else : print "Can not find the transfer file" # ----------------------------結果----------------------------------------------- ''' Before sftp get command Connected to 192.168.233.133. ----------------- After sftp get command get /home/python/test.txt Fetching /home/python/test.txt to test.txt /home/python/test.txt100%7325.2KB/s00:00 ----------------- After sftp bye get /home/python/test.txt Fetching /home/python/test.txt to test.txt /home/python/test.txt100%7325.2KB/s00:00 ----------------- sftp> get /home/python/test.txt Fetching /home/python/test.txt to test.txt /home/python/test.txt100%7325.2KB/s00:00 sftp> Make sure transfer successfully '''