Python利用pexpect库实现FTP自动化交互封装

Ada
Ada
发布时间:2026-10-15| 5人浏览过
原创

本文介绍如何使用Python的pexpect库对FTP交互进行封装。通过spawn类控制子进程,实现自动登录、文件上传下载及异常处理。文章详细解析了spawn类的expect与send方法,以及run函数的用法,提供了完整的代码示例,帮助开发者实现无需人工干涉的FTP自动化操作。

使用工具:

  • pexpect库

pexpect可以视为Linux环境下expect命令的Python封装版本。借助该库,能够对ssh、ftp、passwd、telnet等命令执行自动交互,无需人工干预即可达成自动化目标。例如,可以模拟FTP登录过程中的所有交互步骤,包括输入主机地址、用户名和密码,以及执行文件的上传和下载操作;若遇到异常情况,还能进行自动化的错误处理。

FTP登录脚本

实现登录、文件上传与下载功能

import pexpect

class  FTP(object):
    def __init__(self,ip:str,user,passwd) : #初始化这些函数
        self.ip = ip
        self.user=user
        self.passwd = passwd
        self.child = None

    def ftp_open(self):
        self.child = pexpect.spawnu(f'10.0.0.1')
        # print({self.ip})
        self.child.expect(f'username')
        self.child.sendline(f'username')

        self.child.expect('(?i)password')
        self.child.sendline(f'password')
        self.child.expect('ftp> ',timeout=60)


    def ftp_up_down(self):        
        self.child.sendline('put /tmp/test.dat /pub/test002.dat')
        self.child.expect('ftp> ',timeout=60)       
        self.child.sendline('get /pub/test002.dat /tmp/test003.dat')
        self.child.expect('ftp> ',timeout=60)

    def ftp_up_down_port(self):   
        self.child.sendline('passive')
        self.child.expect('ftp> ',timeout=60)       
        self.child.sendline('put /tmp/test.dat pub/test002.dat')
        self.child.expect('ftp> ',timeout=60)    
        self.child.sendline('get /pub/test002.dat /tmp/test003.dat')
        self.child.expect('ftp> ',timeout=60)

    def ftp_close(self):
        self.child.sendline('bye')

该方法封装的优势在于: 1. 将登录、上传、下载和退出操作拆分为独立方法,便于调用。 2. 参数传递灵活,可根据需要任意增加或修改函数参数。

pexpect组件简介

1. spawn类

spawn是pexpect的核心接口,主要功能是启动和控制子应用程序。spawn()中可指定系统命令,但它不会解析shell命令中的元字符,包括重定向符“>”、管道符“|”或通配符“*”。不过,我们可以将包含这三个特殊元字符的命令作为/bin/bash的参数进行调用,例如:

she = pexpect.spawn(‘/bin/bash –c “cat /etc/passwd | grep root > log.txt”')
she.expect(pexpect.EOF)

spawn支持使用Python列表来替代参数项,比如上述命令可改写为:

command = ‘cat /etc/passwd | grep root > log.txt'

she = pexpect.spawn(‘/bin/bash',[‘-c',command])

she.expect(pexpect.EOF)

(1)expect方法:该方法定义了子程序输出的匹配规则。也可以使用列表进行匹配,返回值是一个下标值;如果列表中有多个元素被匹配,则返回最先出现的字符的下标值。 (2)read方法:向子程序发送响应命令,其作用相当于代替键盘输入。

send(self,s)     发送命令,不回车
sendline(self,s='') 发送命令,回车
sendcontrol(self,char)      发送控制字符test.sendcontrol(‘c')等价于“ctrl+c”
sendeof()    发送eof

2. run函数

run是使用pexpect封装的调用外部命令的函数,类似于os.system()或os.popen()方法。不同的是,使用run可以同时获取命令的输出结果及其退出状态码。

pexpect.run('ssh xxx@x.x.x.x',events={'password:':'xxx'})

events是一个字典

到此这篇关于Python对FTP交互封装的实现的文章就介绍到这了,更多相关Python FTP交互封装内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。