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.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
'''


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM