python中FTP上传和下载
写这篇文章方便以后遇到需要定期去上传或下载时直接可以此简单模板。
1.python中FTP上传
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
#/usr/bin/python
# -*- coding: utf-8 -*-
import
datetime
import
time
import
sys
import
os
import
ftplib
def
Upload_File():
ftp
=
ftplib.FTP()
TODAY
=
time.strftime(
'%Y-%m-%d'
)
FTPIP
=
"10.10.10.10"
#FTP地址
FTPPORT
=
21
#FTP端口号
USERNAME
=
"user"
#FTP用户名
USERPWD
=
"passwd"
#FTP密码
ftp.connect(FTPIP, FTPPORT)
ftp.login(USERNAME,USERPWD)
ftp.set_pasv(
0
)
#打开主动模式
CURRTPATH
=
"log"
LPath
=
"/data/python/study/"
ftp.cwd(CURRTPATH)
os.chdir(LPath)
UploadLocalFilename
=
LPath
+
"code"
+
TODAY
+
".txt"
f
=
open
(UploadLocalFilename,
'rb'
)
ftp.storbinary(
'STOR codes.py'
,f,
1024
)
#ftp.storbinary('STOR %s' % os.path.basename(UploadLocalFilename),f,1024)
f.close()
ftp.close()
Upload_File()
#调用函数
|
2.python中FTP下载
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import
sys
import
ftplib
import
datetime
import
os
import
commands
def
Down_File():
ftp
=
ftplib.FTP()
DATE
=
datetime.date.today().strftime(
"%y%m%d"
)
RPATH
=
"hunk"
LPATH
=
"/home/website/imoney/log"
FTPIP
=
"10.10.10.10"
FTPPORT
=
21
USERNAME
=
"user"
USERPWD
=
"passwd"
ftp.connect(FTPIP, FTPPORT)
ftp.login(USERNAME,USERPWD)
ftp.set_pasv(
0
)
#打开主动模式
ftp.cwd(RPATH)
os.chdir(LPATH)
DownLocalFilename
=
"access% s_log.gz"
%
DATE
f
=
open
(DownLocalFilename,
'wb'
)
DownRoteFilename
=
"access% s_log.gz"
%
DATE
try
:
ftp.retrbinary(
'RETR '
+
DownRoteFilename ,f.write,
1024
)
#可以下载较大文件
except
Exception,e:
print
"Down access% s_log.gz is error: "
%
DATE
+
str
(e)
sys.exit()
f.close()
ftp.close()
Down_File()
#调用函数
|
本文转自独弹古调 51CTO博客,原文链接http://blog.51cto.com/hunkz/1755135:,如需转载请自行联系原作者