日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達者為師

網(wǎng)站首頁 編程語言 正文

Python對FTP交互封裝的實現(xiàn)_python

作者:白舟的博客 ? 更新時間: 2022-08-04 編程語言

使用工具:

  • pexpect庫

pexpect可以理解為Linux下expect(不知道的可以百度下linux expect)的python封裝。
通過pexpect可以實現(xiàn)對ssh、ftp、passwd、telnet等命令進行自動交互,而無需人工干涉來達到自動化的目的。
比如我們可以模擬一個FTP登錄時的所有交互,包括輸入主機地址、用戶名、密碼,還有對文件上傳下載操作等等,若出現(xiàn)異常,我們也可以進行自動化處理。

ftp登錄腳本

實現(xiàn)登錄,文件上傳下載

import pexpect

class ?FTP(object):
? ? def __init__(self,ip:str,user,passwd) : #初始化這些函數(shù)
? ? ? ? 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')

該方法實現(xiàn)封裝的好處:
1.將登錄上傳下載退出分為不同方法,方便調(diào)用
2.傳參靈活,可以任意增加或修改函數(shù)

pexpect組件簡介

1. spawn類

spanw是pexpect的主要接口,功能就是啟動和控制子應(yīng)用程序,spawn()中可以是系統(tǒng)中的命令,但是不會解析shell命令中的元字符,包括重定向“>”,管道符“|”或者通配符“*”,但是我們可以將含有這三個特殊元字符的命令作為/bin/bash的參數(shù)進行調(diào)用,例如:

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

spawn支持使用python列表來代替參數(shù)項,比如上述命令可變?yōu)椋?/p>

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

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

she.expect(pexpect.EOF)

(1)expect方法:expect定義了子程序輸出的匹配規(guī)則。也可使用列表進行匹配,返回值是一個下標(biāo)值,如果列表中有多個元素被匹配,則返回的是最先出現(xiàn)的字符的下標(biāo)值。
(2)read方法:向子程序發(fā)送響應(yīng)命令,可以理解為代替了我們的鍵盤輸入。

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

2. run函數(shù)

run是使用pexpect進行封裝的調(diào)用外部命令的函數(shù),類似于os.system()或os.popen()方法,不同的是,使用run可以同時獲得命令的輸出結(jié)果及其命令的退出狀態(tài)。

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

events是個字典

原文鏈接:https://blog.csdn.net/qq_45175681/article/details/124165543

欄目分類
最近更新