网络编程
位置:首页>> 网络编程>> Python编程>> Python对FTP交互封装的实现

Python对FTP交互封装的实现

作者:白舟的博客  发布时间:2023-05-18 15:12:14 

标签:Python,FTP,交互

使用工具:

  • pexpect库

pexpect可以理解为Linux下expect(不知道的可以百度下linux expect)的python封装。
通过pexpect可以实现对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类

spanw是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方法: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是个字典

来源:https://blog.csdn.net/qq_45175681/article/details/124165543

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com