python ftp操作脚本&常用函数
需求:快速进行ftp上传 ,下载,查询文件
原来直接在shell下操作:
需要【连接,输用户名,输密码,单文件操作,存在超时限制】
太过于繁琐,容易操作失败
脚本改进:
一句命令,搞定多文件上传,下载,查询,列表等操作
后期可以加入更强大的功能
直接上脚本:
- #!/usr/bin/python
- #ftp.py
- #this script is used to make some ftp operations more convenient
- #add upload and download operations 20111210 version0.1
- import sys,os,ftplib,socket
- CONST_HOST = "your ftp host or ip"
- CONST_USERNAME = "your username"
- CONST_PWD = "your password"
- 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()
- 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):
- print(("UPLOAD: %s "+COLOR_GREEN+"SUCCESS"+COLOR_NONE)%up_file)
- else:
- print(("UPLOAD: %s "+COLOR_RED+"FAILED"+COLOR_NONE)%up_file)
- 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):
- print(("DOWNLOAD: %s "+COLOR_GREEN+"SUCCESS"+COLOR_NONE)%down_file)
- else:
- print(("DOWNLOAD: %s "+COLOR_RED+"FAILED"+COLOR_NONE)%down_file)
- 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)
- 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) 创建远程目录
python ftp操作脚本&常用函数的更多相关文章
- Python学习笔记之常用函数及说明
Python学习笔记之常用函数及说明 俗话说"好记性不如烂笔头",老祖宗们几千年总结出来的东西还是有些道理的,所以,常用的东西也要记下来,不记不知道,一记吓一跳,乖乖,函数咋这么多 ...
- 1. python 字符串简介与常用函数
1. python中的字符串简介与常用函数 在python中,字符串变成了一个强大的处理工具集,他是不可变的,也就是说字符串包含字符与字符的顺序,他不可以原处修改 字符串是我们后面需要学习的稍大一点的 ...
- python for循环及常用函数
python for循环 格式: for iterating_var in sequence: statements(s) ###################################### ...
- PHP操作文件常用函数
[获取文件信息的函数] basename($path[,扩展名]) 返回文件路径中去掉路径后的文件名称."/root/a.txt"输出a.txt;带上.txt输出a. dirnam ...
- Python文件或目录操作的常用函数
◆ os.listdir(path) Return a list containing the names of the entries in the directory given by path. ...
- NPOI操作Excel常用函数
最近因项目接触了NPOI,感觉还是蛮不错的,网络上的教程普遍版本较老,本篇记录所常用操作,采用NPOI 2.0版本. 推荐: NPOI官方网站 NPOI 1.2.4/1.2.5 官方教程 新建Exce ...
- Python之Numpy库常用函数大全(含注释)
前言:最近学习Python,才发现原来python里的各种库才是大头! 于是乎找了学习资料对Numpy库常用的函数进行总结,并带了注释.在这里分享给大家,对于库的学习,还是用到时候再查,没必要死记硬背 ...
- Python之Numpy库常用函数大全(含注释)(转)
为收藏学习,特转载:https://blog.csdn.net/u011995719/article/details/71080987 前言:最近学习Python,才发现原来python里的各种库才是 ...
- c语言字符串操作,及常用函数
一,字符串操作 1 . strcpy : 拷贝 char *stpcpy(char *destin, char *source); 2 . strcat : 拼接 char *strcat(char ...
随机推荐
- c++刷题(21/100)树的打印、矩阵覆盖和括号生成
题目一:把二叉树打印成多行 从上到下按层打印二叉树,同一层结点从左至右输出.每一层输出一行. 思路:一开始以为2维的vector可以直接访问,但是试了是不行,会报错,vector在有值之前不能直接访问 ...
- 2017ACM暑期多校联合训练 - Team 9 1005 HDU 6165 FFF at Valentine (dfs)
题目链接 Problem Description At Valentine's eve, Shylock and Lucar were enjoying their time as any other ...
- 【译】第十篇 Integration Services:高级事件行为
本篇文章是Integration Services系列的第十篇,详细内容请参考原文. 简介在前一篇, we introduced fault tolerance by examining method ...
- mysql状态查看 QPS/TPS/缓存命中率查看【转】
运行中的mysql状态查看 对正在运行的mysql进行监控,其中一个方式就是查看mysql运行状态. (1)QPS(每秒Query量) QPS = Questions(or Queries ...
- 缓存数据库-redis安装和配置
一:redis安装 python操作redis分为两部分,一为安装redis程序 二是安装支持python操作redis的模块 1)安装redis redis 官方网站:http://www.redi ...
- html5拖拽初窥
说到拖动,大概有两种方式,一种是js实现,之前已经介绍过,今天来讲解另外一种方式,那就是使用html5实现拖动. css样式 .box { width: 200px; height: 200px; b ...
- 从源码层次分析asterisk如何产生呼叫
老规矩,看别人是怎么搞的 http://blog.chinaunix.net/uid-14723273-id-1739552.html over...
- MySQL基础 - 数据库备份
出于安全考虑,数据库备份是必不可少的,毕竟对于互联网公司数据才是价值的源泉~ 距离mysql账号为icebug,密码为icebug_passwd, 数据库为icebug_db mysqldump -u ...
- mysql数据库主从同步复制原理
MySQL的Replication(英文为复制)是一个多MySQL数据库做主从同步的方案,特点是异步复制,广泛用在各种对MySQL有更高性能.更高可靠性要求的场合.与之对应的是另一个同步技术是MySQ ...
- C++之客户消费积分管理系统
之前数据结构课程设计要求做这么一个小程序,现在贴上源码,来和大家进行交流学习,希望大家给出意见和建议 程序以链表为主要数据结构对客户信息进行存储,对身份证号码判断了位数及构成(前十七位为数字,最后一位 ...