Python Pexpect庫的簡單使用方法
簡介
最近需要遠(yuǎn)程操作一個服務(wù)器并執(zhí)行該服務(wù)器上的一個python腳本,查到可以使用Pexpect這個庫。記錄一下。
什么是Pexpect?Pexpect能夠產(chǎn)生子應(yīng)用程序,并控制他們,并能夠通過期望模式對子應(yīng)用的輸出做出反應(yīng)。Pexpect允許你的腳本產(chǎn)生子應(yīng)用、控制他們像一個人類在輸入命令一樣。
Pexpect使用在自動交互的應(yīng)用,例如SSH、SFTP、PASSWD、TELNET。它可以被應(yīng)用在使用自動設(shè)置腳本為不同的服務(wù)器自動地重復(fù)的安裝軟件包。也可以被應(yīng)用在自動的軟件測試。
Pexpect的主要特點(diǎn)是需要Python的基本庫pty,這個庫只有在類Unix系統(tǒng)上才有
Pexpect關(guān)于SSH的使用
注:測試,我們直接用虛擬機(jī)本機(jī)ssh本機(jī)
環(huán)境
1. win10 物理機(jī)
2. Vmware Centos 虛擬機(jī)
3. Xshell
4. 虛擬機(jī)python安裝pexpect:pip install pexpect
在虛擬機(jī)創(chuàng)建一個 python文件
#-*- coding:UTF-8 -*- import pexpect # 定義ssh連接 def ssh(user,host,password,command): #創(chuàng)建子應(yīng)用,命令是 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有時候提示你是否確認(rèn)連接 # 2 :提示輸入密碼 # 3 :匹配到#號,表示命令已經(jīng)執(zhí)行完畢。沒用到 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 # 提示是否確認(rèn)連接 if i == 1: child.sendline ('yes') # 我們輸入yes child.expect ('password: ')# 輸入yes后 子程序應(yīng)該提示輸入密碼,我們再次期待password i = child.expect([pexpect.TIMEOUT, 'password: ']) #超時 if i == 0: # Timeout return None # 不考慮其他情況,走到此處時,要么timeout 已經(jīng)return ,要么等待輸入密碼 #輸入密碼 child.sendline(password) # 返回子程序 return child if __name__ =='__main__': try: # 配置數(shù)據(jù) 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就是我們要的數(shù)據(jù),有時候還會在 after中 print child.before print child.after except Exception,e: print str(e) # 最終的顯示結(jié)果是 test.py中打印的hahaha結(jié)果, [root@localhost python]# python test_pexpect.py hahaha <class 'pexpect.exceptions.EOF'>
我們嘗試一下開兩個虛擬機(jī)的情況
上面的代碼只需要更改ip user password即可
# ip 192.168.233.133 # user root # 在另一臺虛擬機(jī)的相同位置創(chuàng)建/home/pyhton/test.py 內(nèi)容如下 if __name__=="__main__": print "another virual machine hahaha" # 打印結(jié)果 [root@localhost python]# python test3.py another virual machine hahaha <class 'pexpect.exceptions.EOF'>
Pexpect 關(guān)于 SFTP的使用
與ssh相同,就是使用python在當(dāng)前機(jī)器上輸入sftp ip 然后期望結(jié)果,輸入密碼,并發(fā)送get下載文件即可。
注:使用的時候發(fā)現(xiàn)一點(diǎn)注意:在每次執(zhí)行sendline之前 都需要重新期望一下當(dāng)前的sftp>,或者在每次輸入sendline之后重新期望一下sftp>。也就是期望到這行,否則輸入的命令都沒有反應(yīng),我理解是遠(yuǎn)程連接的服務(wù)器有輸出時候當(dāng)前的位置可能不在sftp>這里所以在sendline的任何東西都是無意義的。如果這個解釋不對望高人指點(diǎn)一下,
# --*-- coding:utf-8 --*-- import pexpect import os import time def sftp(ip , password , command): # 創(chuàng)建子應(yīng)用 child = pexpect.spawn("sftp %s"%(ip)) i = child.expect([pexpect.TIMEOUT,'password:']) # 超時 if i == 0 : print "Timeout" return None # 準(zhǔn)備輸入密碼 if i == 1 : # 輸入密碼 child.sendline(password) j = child.expect([pexpect.TIMEOUT,'sftp>']) # 超時 if j == 0: print "Timeout" return None # 匹配到進(jìn)入sftp命令模式 if j==1: print 'Before sftp get command' print child.before print "-----------------" #發(fā)送命令 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" # ----------------------------結(jié)果----------------------------------------------- ''' 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.txt 100% 73 25.2KB/s 00:00 ----------------- After sftp bye get /home/python/test.txt Fetching /home/python/test.txt to test.txt /home/python/test.txt 100% 73 25.2KB/s 00:00 ----------------- sftp> get /home/python/test.txt Fetching /home/python/test.txt to test.txt /home/python/test.txt 100% 73 25.2KB/s 00:00 sftp> Make sure transfer successfully '''
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
利用 Flask 動態(tài)展示 Pyecharts 圖表數(shù)據(jù)方法小結(jié)
本文將介紹如何在 web 框架 Flask 中使用可視化工具 pyecharts, 看完本教程你將掌握幾種動態(tài)展示可視化數(shù)據(jù)的方法。感興趣的朋友跟隨小編一起看看吧2019-09-09python實(shí)現(xiàn)DES加密解密方法實(shí)例詳解
這篇文章主要介紹了python實(shí)現(xiàn)DES加密解密方法,以實(shí)例形式較為詳細(xì)的分析了基于Python實(shí)現(xiàn)的DES加密與解密技巧,需要的朋友可以參考下2015-06-06pycharm實(shí)現(xiàn)增加運(yùn)行時內(nèi)存
這篇文章主要介紹了pycharm實(shí)現(xiàn)增加運(yùn)行時內(nèi)存方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-02-02python 多線程實(shí)現(xiàn)多任務(wù)的方法示例
本文主要介紹了python 多線程實(shí)現(xiàn)多任務(wù)的方法示例,文中通過示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-07-07詳解Numpy數(shù)組轉(zhuǎn)置的三種方法T、transpose、swapaxes
這篇文章主要介紹了詳解Numpy數(shù)組轉(zhuǎn)置的三種方法T、transpose、swapaxes,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-05-05Python高級應(yīng)用探索之元編程和并發(fā)編程詳解
Python作為一種簡單易用且功能強(qiáng)大的編程語言,廣泛應(yīng)用于各個領(lǐng)域,本文主要來和大家一起探索一下Python中的優(yōu)化技巧、元編程和并發(fā)編程,希望對大家有所幫助2023-11-11