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 ...
随机推荐
- data-ng-hide 指令
<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content=&q ...
- papers-06-07
A simple neural network module for relational reasoning Visual Interaction Networks 今天被这两篇文章的工作刷屏,说实 ...
- 大白话解释IP多播
多播引入 比方说我是一个班主任,管着三个班,每个班30个人,每个班有自己的班长.领导让我宣传19大视 频报告,我这里有源文件.对于普通的单播我需要复制90个副本,给各个班长每人30份,然后班 长在自己 ...
- 【2017 ICPC亚洲区域赛沈阳站 K】Rabbits(思维)
Problem Description Here N (N ≥ 3) rabbits are playing by the river. They are playing on a number li ...
- 【TOJ 3369】CD(二分)
描述 Jack and Jill have decided to sell some of their Compact Discs, while they still have some value. ...
- AOJ 0531 坐标离散化
涂色:(日文题目,自己翻译成了中文)为了宣传信息竞赛,要在长方形的三合板上喷油漆来制作招牌.三合板上不需要涂色的部分预先贴好了护板.被护板隔开的区域要涂上不同的颜色,比如上图就应该涂上5种颜色. 请编 ...
- 根据坐标计算距离(mysql函数)
CREATE DEFINER=`root`@`localhost` FUNCTION `getDistance`(lng1 ) BEGIN DECLARE result double; DECLARE ...
- 两台Linux主机 scp免密传输
两台服务器IP如下配置 Linux1: 10.0.0.1 Linux2: 10.0.0.2 Linux1服务器执行如下操作: # ssh-keygen -t rsa 然后一直回车就行 # sud ...
- 添加fileinfo扩展
首先声明:笔者用的是军哥的lnmp一键安装包!链接地址:https://lnmp.org 打开upgrade_php.sh配置文件[文件所在位置:~/lnmp1.4/include/upgrade_p ...
- jquery添加html代码的几种方法
经常用jq来DOM添加html代码 就总结了jq里面最常用的动态添加html代码的方法 append在元素内部的尾部加上元素 prepend在元素内部的前部加上元素 after在元素外部的尾部加上元素 ...