类比于shell的expect, python中使用pexpect模块来模拟用户和终端交互。有的时候使用pexpect.sendline发送命令后,在各种条件影响下, 可能并不能保证命令在远端服务器执行成功(例如sftp下执行远端rename/rm,实际文件可能并未成功改名/删除)。这个时候就可能需要获取命令执行结果,然后分析结果来对命令的执行状态进行最终确认!

pexpect模块中可以通过pexpect.before/pexpect.buffer获取命令执行结果:

pexpect.buffer   -- 动态保存每一次expect后的所有内容. before/after都依赖此内容;
pexpect.before -- 匹配到的关键字之外的字符;expect后会设置before/after, 具体参考附录,摘录一段文字如下: There are two important methods in Pexpect – expect() and send() (or sendline() which is like send() with a linefeed). The expect() method waits for the child application to return a given string. The string you specify is a regular expression, so you can match complicated patterns. The send() method writes a string to the child application. From the child’s point of view it looks just like someone typed the text from a terminal. After each call to expect() the before and after properties will be set to the text printed by child application. The before property will contain all text up to the expected string pattern. The after string will contain the text that was matched by the expected pattern. The match property is set to the re match object.

测试 -- 模拟sftp登陆后然后执行ls命令查看远端路径

linux:~ # tree /root/sftp/
/root/sftp/
├── csv
│   ├── .csv
│   └── .csv
└── dat
├── .dat
└── .dat directories, files
linux:~ #
linux:~ # cat pexpect_test.py
import os
import sys
import pexpect def pexpect_get_command_result(command, process, prompt = 'sftp>'):
process.sendline('') # 发送空行, 初始环境
process.expect(prompt)
process.buffer = "" # 清空buffer, 防止互相影响
process.sendline(command)
process.expect(prompt) # expect后得到的expect.before就是命令和执行结果 return process.before.strip() # 返回结果 def pexpect_connect():
process = pexpect.spawn('sftp 127.0.0.1', timeout=30)
index = process.expect(["assword: ", "yes/no", pexpect.EOF, pexpect.TIMEOUT]) if index not in [0, 1]:
print "[-] sftp login failed, due to TIMEOUT or EOF"
return None if 1 == index:
process.sendline("yes")
process.expect("assword: ") process.sendline('passwd') return process if __name__ == '__main__':
process = pexpect_connect()
if process == None:
sys.exit(-1) allpath = ['/root/sftp/dat', '/root/sftp/csv']
for path in allpath:
print pexpect_get_command_result('ls ' + path, process) process.sendline("bye") process.close(force = True)
linux:~ #
linux:~ # python pexpect_test.py
ls /root/sftp/dat
/root/sftp/dat/1000.dat /root/sftp/dat/3000.dat
ls /root/sftp/csv
/root/sftp/csv/1000.csv /root/sftp/csv/3000.csv
linux:~ #

参考

https://pexpect.readthedocs.io/en/stable/
http://www.noah.org/python/pexpect/
https://www.cnblogs.com/zz27zz/p/7918717.html 引用出处:
https://pexpect.readthedocs.io/en/stable/overview.html?highlight=pexpect.buffer

pexpect获取远端命令执行结果的更多相关文章

  1. Go实现ssh执行远端命令及远程终端

    什么是ssh? SSH是一种网络协议,用于计算机之间的加密登录. 如果一个用户从本地计算机,使用SSH协议登录另一台远程计算机,我们就可以认为,这种登录是安全的,即使被中途截获,密码也不会泄露. 互联 ...

  2. Python进阶----SOCKET套接字基础, 客户端与服务端通信, 执行远端命令.

    Python进阶----SOCKET套接字基础, 客户端与服务端通信, 执行远端命令. 一丶socket套接字 什么是socket套接字: ​ ​  ​ 专业理解: socket是应用层与TCP/IP ...

  3. git 学习笔记 —— 获取远端分支并修改后提交至远端仓库

    笔者最近进行开发过程中,所有参与者的代码需要通过 git 上传到远端仓库中,不同的模块对应不同的 git 分支,不同模块的数据需要从远端仓库中获取.这里记录下笔者从远端仓库中获取分支数据,进行修改,最 ...

  4. saltstack命令执行过程

    saltstack命令执行过程 具体步骤如下 Salt stack的Master与Minion之间通过ZeroMq进行消息传递,使用了ZeroMq的发布-订阅模式,连接方式包括tcp,ipc salt ...

  5. ping命令执行过程详解

    [TOC] ping命令执行过程详解 机器A ping 机器B 同一网段 ping通知系统建立一个固定格式的ICMP请求数据包 ICMP协议打包这个数据包和机器B的IP地址转交给IP协议层(一组后台运 ...

  6. 【MongoDB】6.关于MongoDB存储文件的 命令执行+代码执行

    参考:http://www.runoob.com/mongodb/mongodb-gridfs.html 1.命令执行 MongoDB GridFS GridFS 用于存储和恢复那些超过16M(BSO ...

  7. 图解“管道过滤器模式”应用实例:SOD框架的命令执行管道

    管道和过滤器 管道和过滤器是八种体系结构模式之一,这八种体系结构模式是:层.管道和过滤器.黑板.代理者.模型-视图-控制器(MVC) 表示-抽象-控制(PAC).微核.映像. 管道和过滤器适用于需要渐 ...

  8. Linux:命令执行顺序控制与管道

    命令执行顺序控制与管道 顺序执行 简单的顺序命令可以使用符号";"完成,如:sudo apt-get update;sudo apt-get install some-tool;s ...

  9. jenkins远程命令执行利用工具

    昨天看小飞侠写的py的jenkins的脚本,昨天晚上在微信里评论今天写一个JAVA的GUI的tools. 早上花了点时间写一下: code: package com.tools; import jav ...

随机推荐

  1. 122. Best Time to Buy and Sell Stock II ——LeetCode

    Say you have an array for which the ith element is the price of a given stock on day i. Design an al ...

  2. SpeedTree制作超真实老宅

  3. JS JavaScript事件循环机制

    区分进程和线程 进程是cpu资源分配的最小单位(系统会给它分配内存) 不同的进程之间是可以同学的,如管道.FIFO(命名管道).消息队列 一个进程里有单个或多个线程 浏览器是多进程的,因为系统给它的进 ...

  4. Centos6.9 安装Oracle11gR2

    最近在学习怎么安装Centos,在Centos6.9版本安装Oracle数据库.参考了网络上很多文章,终于可以不报错的完成安装了,在这里记录一下 一.需要用到的安装文件 Centos6.9   ps: ...

  5. wsgiref手写一个web服务端

    ''' 通过wsgiref写一个web服务端先讲讲wsgiref吧,基于网络通信其根本就是基于socket,所以wsgiref同样也是通过对socket进行封装,避免写过多的代码,将一系列的操作封装成 ...

  6. 【TOJ 1449】Area of Circles II(求不同位置的两圆面积之和)

    描述 There are two circles on the plane. Now you must to calculate the area which they cover the plane ...

  7. leetcode笔记(七)529. Minesweeper

    题目描述 Let's play the minesweeper game (Wikipedia, online game)! You are given a 2D char matrix repres ...

  8. ABAP术语-Authorization

    Authorization 原文:http://www.cnblogs.com/qiangsheng/archive/2007/12/18/1004059.html Authority to exec ...

  9. 解决Nginx: [error] open() "/usr/local/Nginx/logs/Nginx.pid" failed(2:No such file or directory)

    /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf

  10. centos7中vsftp的搭建

    开启vsftpd:service vsftpd start关闭vsftp:service vsftpd stop 安装vsftpd: yum -y install vsftpd 建立vsftpd帐号: ...