pexpect获取远端命令执行结果
类比于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获取远端命令执行结果的更多相关文章
- Go实现ssh执行远端命令及远程终端
什么是ssh? SSH是一种网络协议,用于计算机之间的加密登录. 如果一个用户从本地计算机,使用SSH协议登录另一台远程计算机,我们就可以认为,这种登录是安全的,即使被中途截获,密码也不会泄露. 互联 ...
- Python进阶----SOCKET套接字基础, 客户端与服务端通信, 执行远端命令.
Python进阶----SOCKET套接字基础, 客户端与服务端通信, 执行远端命令. 一丶socket套接字 什么是socket套接字: 专业理解: socket是应用层与TCP/IP ...
- git 学习笔记 —— 获取远端分支并修改后提交至远端仓库
笔者最近进行开发过程中,所有参与者的代码需要通过 git 上传到远端仓库中,不同的模块对应不同的 git 分支,不同模块的数据需要从远端仓库中获取.这里记录下笔者从远端仓库中获取分支数据,进行修改,最 ...
- saltstack命令执行过程
saltstack命令执行过程 具体步骤如下 Salt stack的Master与Minion之间通过ZeroMq进行消息传递,使用了ZeroMq的发布-订阅模式,连接方式包括tcp,ipc salt ...
- ping命令执行过程详解
[TOC] ping命令执行过程详解 机器A ping 机器B 同一网段 ping通知系统建立一个固定格式的ICMP请求数据包 ICMP协议打包这个数据包和机器B的IP地址转交给IP协议层(一组后台运 ...
- 【MongoDB】6.关于MongoDB存储文件的 命令执行+代码执行
参考:http://www.runoob.com/mongodb/mongodb-gridfs.html 1.命令执行 MongoDB GridFS GridFS 用于存储和恢复那些超过16M(BSO ...
- 图解“管道过滤器模式”应用实例:SOD框架的命令执行管道
管道和过滤器 管道和过滤器是八种体系结构模式之一,这八种体系结构模式是:层.管道和过滤器.黑板.代理者.模型-视图-控制器(MVC) 表示-抽象-控制(PAC).微核.映像. 管道和过滤器适用于需要渐 ...
- Linux:命令执行顺序控制与管道
命令执行顺序控制与管道 顺序执行 简单的顺序命令可以使用符号";"完成,如:sudo apt-get update;sudo apt-get install some-tool;s ...
- jenkins远程命令执行利用工具
昨天看小飞侠写的py的jenkins的脚本,昨天晚上在微信里评论今天写一个JAVA的GUI的tools. 早上花了点时间写一下: code: package com.tools; import jav ...
随机推荐
- scala性能测试
主要对比scala 的for, while循环,以及和java for while循环作对比 scala代码 object TestScalaClass { var maxindex = 100000 ...
- lucene&solr学习——solr学习(一)
1.什么是solr solr是Apache下的一个顶级开源项目,采用Java开发,它是基于Lucene的全文检索服务器.Solr提供了比lucene风味丰富的查询语言,同时实现了可配置,可扩展,并对索 ...
- sql中 decode() 的用法
sql中 decode() 的用法 SELECT ID,DECODE(inParam,'Param','value1' ,'value2') name FROM yytj2018 如果 inParam ...
- vue组件原生事件以及路由
1.组件 组件就是可以扩展HTML元素,封装可重用的HTML代码,可以将组件看作自定义的HTML元素 1.1组件注册 全局注册: 组件注册时,需要给他一个名字,如下: Vue.component('m ...
- Python 学习笔记(七)Python字符串(三)
常用字符串方法 split() 分割字符串,指定分隔符对字符串进行分割 join() 将序列中的元素以指定的字符连接生成一个新的字符串 str.strip() 用于移除字符串头尾指定的字符(默认 ...
- 菜鸟崛起 DB Chapter 3 MySQL 5.6的基本操作
3 MySQL的基本操作 上面我们学习一如何安装数据库,那么这节我们来认识一下数据库: 我们在MySQL安装后,在data目录下会自动生成几个必须的数据库,可以使用SHOW DATABASES语句 ...
- Struts2中期(这框架目前正处于淘汰状态)
Struts2的第二天 Struts2的第二天的内容 1. Struts2框架中的Servlet的API的使用 2. Struts2中Action接收请求参数 3. Struts2中自定义拦截器 案例 ...
- poj 2553 The Bottom of a Graph : tarjan O(n) 存环中的点
/** problem: http://poj.org/problem?id=2553 将所有出度为0环中的点排序输出即可. **/ #include<stdio.h> #include& ...
- Laravel 集合的处理
其中的方法有: $arrs = collect($arr)->collapse()->collapse() //去除最外一层数组,不论最外层数组时否有值,都会去除掉 collect($ar ...
- CentOS查看占用端口并关闭
1.查看占用的端口号 netstat -lnp|grep 80 #80 是你需要查看的端口号 二.查看进程的详细信息 ps 29280 #查看进行信息,是否是自己要找的进程 三.杀掉进程 kill ...