Python Pexpect庫的簡單使用

2022-02-02 00:35:08 字數 4889 閱讀 3085

最近需要遠端操作乙個伺服器並執行該伺服器上的乙個python指令碼,查到可以使用pexpect這個庫。記錄一下。

什麼是pexpect?pexpect能夠產生子應用程式,並控制他們,並能夠通過期望模式對子應用的輸出做出反應。pexpect允許你的指令碼產生子應用、控制他們像乙個人類在輸入命令一樣。

pexpect使用在自動互動的應用,例如ssh、sftp、passwd、telnet。它可以被應用在使用自動設定指令碼為不同的伺服器自動地重複的安裝軟體包。也可以被應用在自動的軟體測試。

pexpect的主要特點是需要python的基本庫pty,這個庫只有在類unix系統上才有

注:測試,我們直接用虛擬機器本機ssh本機

1. win10 物理機

2. vmware centos 虛擬機器

3. xshell

4. 虛擬機器python安裝pexpect:pip install pexpect

#-*- 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

上面的**只需要更改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

注:使用的時候發現一點注意:在每次執行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

'''

求助python pexpect報錯

不知道為什麼 在h3c cisco裝置使用都是正常的,在某乙個型號交換機下面就報錯,請大家幫忙找下錯誤在 import pexpect import sys import datetime import os today datetime.date.today strftime y m d path...

python pexpect 自動連線ssh

使用python pexpect 1.首先是安裝 前提是python2.5以上你已經安裝好了 tar xzvf pexpect 2.1.orig.tar.gz cd pexpect 2.1 python setup.py install 沒許可權時,記得sudo 3.編寫linkssh.py usr...

python pexpect模組詳解附常用指令碼

wgettar zxvf pexpect 2.4.tar.gz cd pexpect 2.4 python setup.py install spawn是pexpect模組主要的類,用以實現啟動子程式,它有豐富的方法與子程式互動從而實現使用者對子程式的控制。示例 child pexpect.spaw...