blog.zhuohua.store's Archiver

admin 发表于 2019-9-26 14:33

Linux使用内置模块ftplib

操作系统的版本信息:
[root@Zabbix_server_01 ~]# cat /etc/redhat-release
CentOS release 6.9 (Final)
[root@Zabbix_server_01 ~]#
[root@Zabbix_server_01 ~]# uname -r
2.6.32-696.el6.x86_64

Python的版本信息:
[root@Zabbix_server_01 ~]# python3 --version
Python 3.6.8





######
例子一:
上传FTP文件:

[root@Zabbix_server_01 ~]# cat xx.py
#coding=utf-8
import ftplib

def ftp_upload(file_remote,file_local):

        global f
        try:
                host = '192.168.168.154' #远程FTP服务器的IP地址
                username = 'zhuohua' #远程FTP用户
                password = '111' #远程FTP用户的密码

                f = ftplib.FTP(host)
                f.login(username, password)
                f.encoding = 'utf-8'
               
                pwd_path = f.pwd() #默认的工作目录就是FTP根目录
                print("FTP当前工作目录:", pwd_path)
               
                bufsize = 1024  #设置缓冲器大小
                fp = open(file_local, 'rb')
                f.storbinary('STOR ' + file_remote, fp, bufsize) #以二进制形式上传文件
                fp.close()
               
        except Exception as e:
                print(f"本地文件{file_local}上传失败,原因: {e}")
               
        else:
                print(f"本地文件{file_local}上传成功。")
               
        finally:
                f.quit()
       
if __name__ == '__main__':

        file_remote = 'zabbix.conf.php' #远程文件
        file_local = '/root/zabbix.conf.php' #本地文件
        ftp_upload(file_remote,file_local)
       
        file_remote = 'Python-3.6.8_1.tgz' #远程文件,如果文件名称重复会被直接覆盖(上传成功)
        file_local = '/root/Python-3.6.8.tgz' #本地文件;本地文件名与远程文件名可以不一样
        ftp_upload(file_remote,file_local)

        file_remote = '文件_c.txt' #远程文件的名称可以包含中文
        file_local = '/share/文件_c.txt' #本地文件的名称也可以包含中文
        ftp_upload(file_remote,file_local) #多次执行函数,就可以一次性上传多个文件

       
脚本运行的结果:
[root@Zabbix_server_01 ~]# python3 xx.py
FTP当前工作目录: /
本地文件/root/zabbix.conf.php上传成功。
FTP当前工作目录: /
本地文件/root/Python-3.6.8.tgz上传成功。
FTP当前工作目录: /
本地文件/share/文件_c.txt上传成功。
[root@Zabbix_server_01 ~]#





######
例子二:
创建FTP子目录/dir_1:

[root@Zabbix_server_01 ~]# cat xx.py
#coding=utf-8
import ftplib

def ftp_mkd(my_dir):

        try:
                host = '192.168.168.154'
                username = 'zhuohua'
                password = '111'

                f = ftplib.FTP(host)
                f.login(username, password)
                f.encoding = 'utf-8'
               
                f.mkd(my_dir)
               
        except Exception as e:
                print(f"FTP子目录{my_dir}创建失败,原因: {e}")
               
        else:
                print(f"FTP子目录{my_dir}创建成功。")
               
        finally:
                f.quit()
       
if __name__ == '__main__':

        ftp_mkd('/dir_1')

       
脚本运行的结果:
[root@Zabbix_server_01 ~]# python3 xx.py
FTP子目录/dir_1创建成功。
[root@Zabbix_server_01 ~]#





######
例子三:
根据当前月份创建FTP子目录:

[root@Zabbix_server_01 ~]# cat xx.py
#coding=utf-8
import ftplib
import time

Key_month = time.localtime()[1]
print(f"当前的月份:{Key_month}")

def ftp_mkd():

        host = '192.168.168.154'
        username = 'zhuohua'
        password = '111'

        f = ftplib.FTP(host)
        f.login(username, password)
        f.encoding = 'utf-8'
       
        my_dir = f"{Key_month}月份报表目录"
        f.mkd(my_dir)
       
        print(f"{my_dir}创建成功。")
               
        f.quit()
       
if __name__ == '__main__':

        ftp_mkd()


脚本运行的结果:
[root@Zabbix_server_01 ~]# python3 xx.py
当前的月份:5
5月份报表目录创建成功。
[root@Zabbix_server_01 ~]#





######

例子四:
显示FTP根目录里的文件、子目录:(不会延伸到子目录的子目录)

[root@Zabbix_server_01 ~]# cat xx.py
#coding=utf-8
import ftplib

def ftp_show():
        try:
                host = '192.168.168.154'
                username = 'zhuohua'
                password = '111'

                f = ftplib.FTP(host)
                f.login(username, password)
                f.encoding = 'utf-8'
               
                pwd_path = f.pwd() #默认的工作目录就是FTP根目录
                print("FTP当前工作目录:", pwd_path)
               
                print("-" * 10)
                print("-" * 10)
                print("FTP根目录下的文件、子目录:")

                lines = []
                f.dir(f"{pwd_path}", lines.append)

                for line in lines:
                        tokens = line.split(maxsplit = 9)
                        name = tokens[8]
                        print(name)
               
        except Exception as e:
                print(f"FTP文件、子目录显示失败,原因: {e}")
               
        else:
                pass
               
        finally:
                f.quit()
       
if __name__ == '__main__':

        ftp_show()
       

脚本运行的结果:
[root@Zabbix_server_01 ~]# python3 xx.py
FTP当前工作目录: /
----------
----------
FTP根目录下的文件、子目录:
5月份报表目录
Python-3.6.8_1.tgz
dir_1
zabbix.conf.php
文件_c.txt
[root@Zabbix_server_01 ~]#





######

例子五:
上传当前日期的php文件到FTP子目录/dir_1:

[root@Zabbix_server_01 ~]# cat xx.py
#coding=utf-8
import ftplib
import datetime

def ftp_upload(file_remote,file_local):
        try:
                host = '192.168.168.154'
                username = 'zhuohua'
                password = '111'

                f = ftplib.FTP(host)
                f.login(username, password)
                f.encoding = 'utf-8'
               
                f.cwd('/dir_1') #切换FTP的工作目录
                pwd_path = f.pwd()
                print("FTP当前工作目录:", pwd_path)
               
                bufsize = 1024
                fp = open(file_local, 'rb')
                f.storbinary('STOR ' + file_remote, fp, bufsize) #以二进制形式上传文件
                fp.close()
               
        except Exception as e:
                print(f"本地文件{file_local}上传失败,原因: {e}")
               
        else:
                print(f"本地文件{file_local}上传成功。")
               
        finally:
                f.quit()
       
if __name__ == '__main__':

        dt = datetime.datetime.now()
        tt = dt.strftime('%Y%m%d')
        print(f"当前的日期:{tt}")

        file_remote = f'zabbix.conf_{tt}.php' #远程文件
        file_local = f'/root/zabbix.conf_{tt}.php' #本地文件
        ftp_upload(file_remote,file_local)


脚本运行的结果:
[root@Zabbix_server_01 ~]# python3 xx.py
当前的日期:20200522
FTP当前工作目录: /dir_1
本地文件/root/zabbix.conf_20200522.php上传成功。
[root@Zabbix_server_01 ~]#





######

例子六:
显示FTP子目录里的文件、子目录:

[root@Zabbix_server_01 ~]# cat xx.py
#coding=utf-8
import ftplib

def ftp_show():
        try:
                host = '192.168.168.154'
                username = 'zhuohua'
                password = '111'

                f = ftplib.FTP(host)
                f.login(username, password)
                f.encoding = 'utf-8'
               
                f.cwd('/dir_1') #切换FTP的工作目录
               
                pwd_path = f.pwd()
                print("FTP当前工作目录:", pwd_path)
               
                print("-" * 10)
                print("-" * 10)
                print(f"FTP子目录{pwd_path}下的文件、子目录:")

                lines = []
                f.dir(f"{pwd_path}", lines.append)

                for line in lines:
                        tokens = line.split(maxsplit = 9)
                        name = tokens[8]
                        print(name)
               
        except Exception as e:
                print(f"FTP文件、子目录显示失败,原因: {e}")
               
        else:
                pass
               
        finally:
                f.quit()
       
if __name__ == '__main__':

        ftp_show()
       
       
脚本运行的结果:
[root@Zabbix_server_01 ~]# python3 xx.py
FTP当前工作目录: /dir_1
----------
----------
FTP子目录/dir_1下的文件、子目录:
zabbix.conf_20200522.php
[root@Zabbix_server_01 ~]#





######

例子七:
把客户端本地目录/root里的log文件全部上传到FTP根目录:
[code][root@Zabbix_server_01 ~]# cat xx.py
#coding=utf-8
import ftplib
import os

def ftp_upload(file_remote,file_local):
        host = '192.168.168.154'
        username = 'zhuohua'
        password = '111'

        f = ftplib.FTP(host)
        f.login(username, password)
        f.encoding = 'utf-8'
               
        f.cwd('/') #切换FTP的工作目录;默认的工作目录就是FTP根目录
               
        pwd_path = f.pwd()
        print("FTP当前工作目录:", pwd_path)
               
        bufsize = 1024
        fp = open(file_local, 'rb')
        f.storbinary('STOR ' + file_remote, fp, bufsize) #以二进制形式上传文件
        fp.close()
        f.quit()

def func1():
        dir_1 = "/root/" #客户端本地文件夹
        K_1 = '.log' #文件后缀

        f = list(os.listdir(dir_1))

        for i in range(len(f)):
                if f[i].endswith(K_1):
                        #print(f[i])
                        ftp_upload(f[i],f[i])
                        print(f"本地文件{f[i]}上传成功。")
                       
if __name__ == '__main__':

        func1()
[/code]
脚本运行的结果:
[root@Zabbix_server_01 ~]# python3 xx.py
FTP当前工作目录: /
本地文件install.log上传成功。
FTP当前工作目录: /
本地文件lnmp-install.log上传成功。
[root@Zabbix_server_01 ~]#





######

例子八:
把FTP根目录里的log文件全部下载到客户端本地的文件夹/share:

[root@Zabbix_server_01 ~]# cat xx.py
#coding=utf-8
import ftplib
import os

def func1(): #判断客户端本地的文件夹/share是否已经存在;假如不存在,就自动创建
        Path_1 = "/share"

        Result_1 = os.path.exists(Path_1)
        #print(Result_1)

        if Result_1 == False:
                os.mkdir(Path_1)

def ftp_download():

        host = '192.168.168.154'
        username = 'zhuohua'
        password = '111'

        f = ftplib.FTP(host)
        f.login(username, password)
        f.encoding = 'utf-8'

        f.cwd('/') #切换FTP的工作目录;默认的工作目录就是FTP根目录
               
        pwd_path = f.pwd()
        print("FTP当前工作目录:", pwd_path)
               
        K_1 = '.log' #文件后缀
       
        for file in f.nlst():
                if file.endswith(K_1):
                        file_local = f"/share/{file}"
                        file_remote = file
               
                        bufsize = 1024
                        fp = open(file_local, 'wb')
                        f.retrbinary('RETR %s' % file_remote, fp.write, bufsize) #以二进制形式下载文件
                        fp.close()
                        print(f"远程文件{file_remote}下载成功。")
               
        f.quit()
       
if __name__ == '__main__':

        func1()
        ftp_download()


脚本运行的结果:
[root@Zabbix_server_01 ~]# python3 xx.py
FTP当前工作目录: /
远程文件install.log下载成功。
远程文件lnmp-install.log下载成功。
[root@Zabbix_server_01 ~]#

[root@Zabbix_server_01 ~]# du -ah /share/*.log
16K     /share/install.log
2.5M    /share/lnmp-install.log
[root@Zabbix_server_01 ~]#





######

例子九:
下载FTP子目录/dir_1里当前日期的php文件到客户端本地:

[root@Zabbix_server_01 ~]# cat xx.py
#coding=utf-8
import ftplib
import datetime,time
import os

Key_month = time.localtime()[1]
print(f"当前的月份:{Key_month}")

def func1(): #根据当前月份创建客户端本地的文件夹

        global Path_1
        Path_1 = f"/root/{Key_month}月份日志目录"

        Result_1 = os.path.exists(Path_1)
        #print(Result_1)

        if Result_1 == False:
                os.mkdir(Path_1)

def ftp_download(file_remote,file_local):
        try:
                host = '192.168.168.154'
                username = 'zhuohua'
                password = '111'

                f = ftplib.FTP(host)
                f.login(username, password)
                f.encoding = 'utf-8'
               
                f.cwd('/dir_1') #切换FTP的工作目录
               
                pwd_path = f.pwd()
                print("FTP当前工作目录:", pwd_path)

                bufsize = 1024 #设置缓冲器大小
                fp = open(file_local, 'wb')
                f.retrbinary('RETR %s' % file_remote, fp.write, bufsize) #以二进制形式下载文件
                fp.close()
               
        except Exception as e:
                print(f"远程文件{file_remote}下载失败,原因: {e}")
               
        else:
                print(f"远程文件{file_remote}成功下载到客户端本地的文件夹{Path_1}。")
               
        finally:
                f.quit()
       
if __name__ == '__main__':

        dt = datetime.datetime.now()
        tt = dt.strftime('%Y%m%d')
        print(f"当前的日期:{tt}")
       
        func1()

        file_remote = f'zabbix.conf_{tt}.php' #远程文件
        file_local = f'{Path_1}/zabbix.conf_{tt}.php' #本地文件
        ftp_download(file_remote,file_local)


脚本运行的结果:
[root@Zabbix_server_01 ~]# python3 xx.py
当前的月份:5
当前的日期:20200522
FTP当前工作目录: /dir_1
远程文件zabbix.conf_20200522.php成功下载到客户端本地的文件夹/root/5月份日志目录。
[root@Zabbix_server_01 ~]#

[root@Zabbix_server_01 ~]# du -ah /root/5月份日志目录/
4.0K    /root/5月份日志目录/zabbix.conf_20200522.php
8.0K    /root/5月份日志目录/
[root@Zabbix_server_01 ~]#





相关文章:
[url=http://blog.zhuohua.store/viewthread.php?tid=161&page=1&extra=#pid162]Windows使用内置模块ftplib[/url]

[url=http://blog.zhuohua.store/viewthread.php?tid=500&page=1&extra=#pid928]Python3命令集[/url]
[url=http://blog.zhuohua.store/viewthread.php?tid=118&extra=page%3D1]自定义函数[/url]
[url=http://blog.zhuohua.store/viewthread.php?tid=137&extra=page%3D1]time模块[/url]

页: [1]

Powered by Discuz! Archiver 7.2  © 2001-2009 Comsenz Inc.