upload_video_ftp.py
3.26 KB
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#encoding=utf-8
#!/usr/bin/env python
# @auther : Ylei
# @date : 2019/9/21
# @File : upload_video_ftp.py
# @Software : PyCharm
#coding: utf-8
import os
from ftplib import FTP
from log_module import logger
def ftpconnect(host, username, password):
try:
ftp = FTP()
ftp.set_debuglevel(2) #打开调试级别2,显示详细信息
ftp.connect(host,21) #连接
ftp.login(username, password) #登录,如果匿名登录则用空串代替即可
#ftp.set_pasv(True)
print('FTP welcome message is :%s' %(ftp.getwelcome()))
return ftp
except Exception as e:
print('TFP connect error: %s' %e)
def downloadfile(ftp,file_name,remotepath=r'/home/ufpt'):
bufsize = 1024 #设置缓冲块大小
fp = open(file_name,'wb') #以写模式在本地打开文件
ftp.retrbinary('RETR %s' %file_name, fp.write, bufsize) #接收服务器上文件并写入本地文件
ftp.set_debuglevel(0) #关闭调试
fp.close() #关闭文件
def uploadfile(ftp,upload_file_path,SBBH,dt,video_ID='123456789',video_format='.avi'):
bufsize = 1024
#log = logger('data_info_ftp.log')
# if remote_path != '/home/ufpt':
# print 'Not in upload directiory,will in upload directiory '
# ftp.cwd(remote_path)
# try:
# ftp.cwd('HwRis')
# except Exception as e:
# print e
# ftp.mkd('HwRis')
# ftp.cwd('HwRis')
# try:
# ftp.cwd('Illegal')
# except Exception as e:
# print e
# ftp.mkd('Illegal')
# ftp.cwd('Illegal')
try:
ftp.cwd(SBBH)
except Exception as e:
print(e)
ftp.mkd(SBBH)
ftp.cwd(SBBH)
try:
ftp.cwd(dt)
except Exception as e:
ftp.mkd(dt)
ftp.cwd(dt)
print(e)
finally:
try:
#print('remote_storage_path is :%s' %ftp.pwd())
#log.debug('remote_storage_path is:%s---file is :%s' %(ftp.pwd(),upload_file_path))
file_handle = open(upload_file_path, "rb")
print(video_ID + '.' + video_format)
ftp.storbinary("STOR %s" % (video_ID + '.' + video_format), file_handle, 1024)
#ftp.storlines('STOR %s' %video.filename,video)###文本文件方式视频文件ftp传输后播放有问题
ftp.close()
os.remove(upload_file_path)
return True
except Exception as e:
os.remove(upload_file_path)
#log.debug('upload errors :%s' %e)
#print('ftp upload error:%s' %e)
#
#
# with open(file_name.filename, 'wb') as fp:
# for line in file_name.readlines():
# fp.write(line)
# ftp.storbinary('STOR %s' %file_name, fp, bufsize) #上传文件
# ftp.set_debuglevel(0)
# fp.close()
if __name__ == "__main__":
# a = r'/a/b/c/aa.txt'
# print os.path.splitext(a)[0]
ip = '192.168.9.62'
username = 'ftpuser'
password = 'yl'
ftp = ftpconnect(ip,username,password)
if ftp:
file_name = '123.txt'
upload_flag = uploadfile(ftp,file_name,'sbbh','20191016')
if upload_flag:
print("OK")
else:
print("SORRY")