惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Troy Hunt's Blog
人人都是产品经理
人人都是产品经理
MongoDB | Blog
MongoDB | Blog
Stack Overflow Blog
Stack Overflow Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Microsoft Security Blog
Microsoft Security Blog
F
Fortinet All Blogs
博客园 - 三生石上(FineUI控件)
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
P
Proofpoint News Feed
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - Franky
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Martin Fowler
Martin Fowler
V
Visual Studio Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Microsoft Azure Blog
Microsoft Azure Blog
云风的 BLOG
云风的 BLOG
G
Google Developers Blog
WordPress大学
WordPress大学
腾讯CDC
J
Java Code Geeks
T
The Blog of Author Tim Ferriss
博客园 - 司徒正美
博客园 - 【当耐特】
小众软件
小众软件
Attack and Defense Labs
Attack and Defense Labs
宝玉的分享
宝玉的分享
Google DeepMind News
Google DeepMind News
罗磊的独立博客
Schneier on Security
Schneier on Security
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
量子位
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
O
OpenAI News
TaoSecurity Blog
TaoSecurity Blog
H
Heimdal Security Blog
Blog — PlanetScale
Blog — PlanetScale
Forbes - Security
Forbes - Security
B
Blog
I
InfoQ
D
DataBreaches.Net
月光博客
月光博客
T
Tenable Blog
S
Security Affairs
C
Check Point Blog
T
Threatpost
C
Cybersecurity and Infrastructure Security Agency CISA
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
www.infosecurity-magazine.com
www.infosecurity-magazine.com

Posts on WKLKEN THINKING

apisix 中的 lrucache apisix 中的服务发现机制 apisix 中的负载均衡 apisix etcd机制 聊聊框架 关于 k8s 的 zero downtime deployment 一些建议 apisix 遇到的一些问题 关于在除夕前一天换了一个洗衣机的故事 Django DRF 性能优化 DRF 的一些实践 Part1: Serializer DRF继承关系图 Better Code: 关于接口的灵活性 新的仓库: wklken/naming 缓存使用的一些经验 Better Code: 抽象: 可扩展性与可维护性的抉择 Better Code: 异常时, 该提示用户哪些信息? Better Code: 更好的异常日志打印 Go: some libs Go: go-redis/cache升级的坑 Go: logrus性能提升 Go: gin validation 远程办公的一点总结 Go: 开发过程中的一些bug 项目管理实践: 风险驱动开发 Go: 一种error wrap调用链处理方式 漫谈技术选型 Go: 基于 apitest 做handler层单元测试 Go: go-sql-driver interpolateparams参数优化 [分享]深度工作 你需要更多的思考时间 Django项目重构小结 工作七年小结: 学习,生活及其他 [分享]bash日常: bash-utils 极客时间推广海报 2017总结: 予时光以意义 k8s APIServer源码: api注册详细细节 k8s APIServer源码: api注册主体流程 k8s APIServer源码: 服务启动 k8s APIServer源码: go-restful框架 重构 - 读书笔记(Python示例) 写给新人的沟通建议 vim 杂谈 - 关于快速编辑 vim 杂谈 - 关于移动 读书笔记-重构: 章11 处理概括关系 读书笔记-重构: 章10 简化函数调用 读书笔记-重构: 章9 简化表达式 读书笔记-重构: 章8 重新组织数据 读书笔记-重构: 章7 在对象之间搬移特性 读书笔记-重构: 章6 重新组织函数 Python 代码规范小结 [分享]关于vim ElasticSearch集群部署文档 Logstash+ElasticSearch处理mysql慢查询日志 [分享]关于代码调试DE那些事 Logstash+ElasticSearch+Kibana- 实现相对通用的数据收集分析 ELK维护的一些点(二) [分享]Python源码剖析-数据结构 一些Centos Python生产环境的部署命令 摘录<<6个月学会任何一种外语>> ELK 维护的一些点 也许是一个新的开始 一些vim的个性化配置 读书笔记-调试九法 这段时间的一些想法 Python 源码阅读 - 垃圾回收机制 我为什么要写博客 APUE笔记-第一章 UNIX基础知识 Python源码阅读-闭包的实现 Python源码阅读-内存管理机制(二) Python源码阅读-内存管理机制(一) Python-基础-数据结构小结 '活动'设计的一些trick 一些简单的Python测试题 我的tmux配置及说明【k-tmux】 Review and Restart 工作四周年小结 vim插件: surround & repeat[成对符号编辑] vim插件: gundo[时光机] vim插件: expand-region[区域选中] vim插件: quickrun[快速执行] vim插件: trailing-whitespace[行尾空格处理] vim插件: closetag[成对标签补全] vim插件: ctrlp[文件搜索] vim插件: airline[状态栏增强] vim插件: theme[主题] vim插件: tagbar[大纲式导航] vim插件: nerdcommenter[快速注释] vim插件: rainbow_parentheses[括号高亮] vim插件: syntastic[语法检查] vim插件: delimitmate[符号自动补全] vim插件: matchit[成对标签跳转] vim插件: easy-align[快速对齐] vim插件: multiple-cursors[多光标操作] vim插件: vim-signature[快速标记跳转] vim插件: easymotion[快速跳转] vim插件: vundle[管理插件] Elasticsearch几个问题的解决 分享一份 Vim 简介PPT k-vim 更新9.0版本 关于知识管理工具的思考
Python实现ftp常用操作[ftplib]
2011-12-10 · via Posts on WKLKEN THINKING

使用到的模块 ftplib

代码托管位置 github-pytools

需求

快速进行ftp上传 ,下载,查询文件

原来直接在shell下操作:需要【连接,输用户名,输密码,单文件操作,存在超时限制】

太过于繁琐,容易操作失败

改进

一句命令,搞定多文件上传,下载,查询,列表等操作

后期可以加入更强大的功能

源代码

#!/usr/bin/python
# -*- coding:utf-8 -*-
#ftp.py
#    wklken@yeah.net
#this script is used to do some operations more convenient via ftp
  #1.[p]upload many files in the same time,show md5s
  #2.[g]download many files in the same time,show md5s
  #3.[l]list all the files on ftp site
  #4.[f]search a file on ftp site,return True or Flase
  #5.[h]show help info

#add upload and download operations  20111210 version0.1
#add md5sum after ops 20120308 version0.2

import sys,os,ftplib,socket

CONST_HOST = "ip"
CONST_USERNAME = "username"
CONST_PWD = "pwd"
CONST_BUFFER_SIZE = 8192

COLOR_NONE = "\033[m"
COLOR_GREEN = "\033[01;32m"
COLOR_RED = "\033[01;31m"
COLOR_YELLOW = "\033[01;33m"

def connect():
    try:
        ftp = ftplib.FTP(CONST_HOST)
        ftp.login(CONST_USERNAME,CONST_PWD)
        return ftp
    except socket.error,socket.gaierror:
        print("FTP is unavailable,please check the host,username and password!")
        sys.exit(0)

def disconnect(ftp):
    ftp.quit()

def upload(ftp, filepath):
    f = open(filepath, "rb")
    file_name = os.path.split(filepath)[-1]
    try:
        ftp.storbinary('STOR %s'%file_name, f, CONST_BUFFER_SIZE)
    except ftplib.error_perm:
        return False
    return True

def download(ftp, filename):
    f = open(filename,"wb").write
    try:
        ftp.retrbinary("RETR %s"%filename, f, CONST_BUFFER_SIZE)
    except ftplib.error_perm:
        return False
    return True

def list(ftp):
    ftp.dir()

def find(ftp,filename):
    ftp_f_list = ftp.nlst()
    if filename in ftp_f_list:
        return True
    else:
        return False

def help():
    print("help info:")
    print("[./ftp.py l]\t show the file list of the ftp site ")
    print("[./ftp.py f filenamA filenameB]\t check if the file is in the ftp site")
    print("[./ftp.py p filenameA filenameB]\t upload file into ftp site")
    print("[./ftp.py g filenameA filenameB]\t get file from ftp site")
    print("[./ftp.py h]\t show help info")
    print("other params are invalid")

def main():
    args = sys.argv[1:]
    if len(args) == 0:
        print("Params needed!")
        sys.exit(0)

    ftp = connect()

    success_list = []
    failed_list = []

    if args[0] == "p":
        f_list = args[1:]

        for up_file in f_list:
        if not os.path.exists(up_file):
            print(("UPLOAD: %s "+COLOR_RED+"FAILED"+COLOR_NONE+"  :file not exist")%up_file)
            continue
        elif not os.path.isfile(up_file):
            print(("UPLOAD: %s "+COLOR_RED+"FAILED"+COLOR_NONE+"  :%s is not a file")%(up_file,up_file))
            continue

        if upload(ftp, up_file):
            success_list.append(up_file)
        else:
            failed_list.append(up_file)
        if len(success_list) > 0 :
        print((COLOR_GREEN + "UPLOAD SUCCESS: %s" + COLOR_NONE)%(" ".join(success_list)))
        print("md5sum:")
        for f in success_list:
            print( os.popen("md5sum " + f).read()[:-1])
        if len(failed_list) > 0:
        print((COLOR_RED + "UPLOAD FAILED: %s" + COLOR_NONE)%(" ".join(failed_list)))

    elif args[0] == "g":
        f_list = args[1:]

        for down_file in f_list:
        if not find(ftp,down_file):
            print(("DOWNLOAD: %s "+COLOR_RED+"FAILED"+COLOR_NONE+"  :%s is not in the ftp site")%(down_file,down_file))
            continue

        if download(ftp, down_file):
            success_list.append(down_file)
        else:
            failed_list.append(down_file)
        if len(success_list) > 0 :
        print((COLOR_GREEN + "DOWNLOAD SUCCESS: %s" + COLOR_NONE)%(" ".join(success_list)))
        print("md5sum:")
        for f in success_list:
            print( os.popen("md5sum " + f).read()[:-1])
        if len(failed_list) > 0:
        print((COLOR_RED + "DOWNLOAD FAILED: %s" + COLOR_NONE)%(" ".join(failed_list)))

    elif args[0] == "l":
        list(ftp)
    elif args[0] == "f":
        f_list = args[1:]
        for f_file in f_list:
        if find(ftp,f_file):
            print(("SEARCH: %s "+COLOR_GREEN+"EXIST"+COLOR_NONE)%f_file)
        else:
            print(("SEARCH: %s "+COLOR_RED+"NOT EXIST"+COLOR_NONE)%f_file)
            if len(f_file) > 3:
            print("Similar File List:")
            s = ftp.nlst()
            print  ", ".join([k for k in s if f_file in k])

    elif args[0] == "h":
        help()
    else:
        print("args are invalid!")
        help()

    disconnect(ftp)

if __name__ == "__main__":
  main()

常用函数

用手册查看,以下只是简略,因为没用用到,[待整理]:

login(user='',passwd='', acct='')     登录到FTP 服务器,所有的参数都是可选的
pwd()                       当前工作目录
cwd(path)                   把当前工作目录设置为path
dir([path[,...[,cb]])       显示path 目录里的内容,可选的参数cb 是一个回调函数,会被传给retrlines()方法
nlst([path[,...])           与dir()类似,但返回一个文件名的列表,而不是显示这些文件名
retrlines(cmd [, cb])       给定FTP 命令(如“RETR filename”),用于下载文本文件。可选的回调函数cb 用于处理文件的每一行
retrbinary(cmd, cb[,bs=8192[, ra]])     与retrlines()类似,只是这个指令处理二进制文件。回调函数cb 用于处理每一块(块大小默认为8K)下载的数据。
storlines(cmd, f)   给定FTP 命令(如“STOR filename”),以上传文本文件。要给定一个文件对象f
storbinary(cmd, f[,bs=8192])    与storlines()类似,只是这个指令处理二进制文件。要给定一个文件对象f,上传块大小bs 默认为8Kbs=8192])
rename(old, new)    把远程文件old 改名为new
delete(path)     删除位于path 的远程文件
mkd(directory)  创建远程目录