Python的Pexpect的简单使用

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python的Pexpect的简单使用相关的知识,希望对你有一定的参考价值。

Pexpect 是一个用来启动子程序并对其进行自动控制的纯 Python 模块。 Pexpect 可以用来和像 ssh、ftp、passwd、telnet 等命令行程序进行自动交互。本文主要是针对ssh远程登录,然后执行简单的新建文件夹与拷贝任务

 

Pexpect 的安装:

下载:https://pypi.python.org/pypi/pexpect/

解压后在目录下运行:python setup.py install

 

Pexpect 的简单使用:

from pexpect import *

user = ‘user‘

host = ‘host‘

password = ‘password‘

 

#实现远程登录host机器并新建/home/download/wangling/test目录

command = ‘sudo ssh -l ‘+user+‘ ‘+host+‘ sudo mkdir -p /home/download/wangling/test‘

child = spawn(command , timeout=10   ) 

child.sendline(password)

 

#实现远程文件拷贝(将本机1.txt文件拷贝到host机器test2目录下2.txt)

command1 = ‘sudo scp /home/download/wangling/test1/1.txt ‘+user+‘@‘+host+‘:/home/download/wangling/test2/2.txt‘

child = spawn(command1 , timeout=10   )

child.sendline(password)

 

以上是关于Python的Pexpect的简单使用的主要内容,如果未能解决你的问题,请参考以下文章

python 终端模拟模块 pexpect

Python学习——pexpect

用pexpect做简单的输出判断

pexpect库run函数的使用详解

python 使用pexpect实现自动交互示例

如何使用 Python pexpect 执行操作系统命令?