实例介绍
【实例截图】
【核心代码】
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"Program for ftp server"
from socketserver import *
from time import *
import os
import loginauth
import traceback
import subprocess
import codecs
import logging
def GetParentPath(strPath):
if not strPath:
return None;
lsPath = os.path.split(strPath);
if lsPath[1]:
return lsPath[0];
lsPath = os.path.split(lsPath[0]);
return lsPath[0];
def ReadFile(filePath,encoding="utf-8"):
with codecs.open(filePath,"r",encoding) as f:
return f.read()
class MyFtp(StreamRequestHandler):
def handle(self):
logger = logging.getLogger("FTP")
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler("ftp.log")
fh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter and add it to the handlers
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
ch.setFormatter(formatter)
fh.setFormatter(formatter)
# add the handlers to logger
logger.addHandler(ch)
logger.addHandler(fh)
# "application" code
__devilcomment = '''
logger.debug("debug message")
logger.info("info message")
logger.warn("warn message")
logger.error("error message")
logger.critical("critical message")
'''
self.client_address[0]
logger.info('%s connected'%self.client_address[0])
self.request.sendall(b'auth')
logger.info('%s Authenticating'%self.client_address[0])
while True:
try:
name,password = self.request.recv(BUFSIZ).decode('utf-8').split()
except:
self.request.sendall(b'fail2login')
continue
auth_result = loginauth.user_Auth(name,password)
if auth_result == 0:
logger.info('%s log in'% name)
self.request.sendall(b'ok2login')
homePath = os.path.abspath('.')
break
elif auth_result == 1:
logger.info('%s Authentiation failed'% name)
self.request.sendall(b'fail2login')
sleep(1)
continue
while True:
try:
recv_data = self.request.recv(BUFSIZ).decode('utf-8')
command = recv_data.split()
if command==[]:
continue
logger.info ('command: ' ' '.join(command))
if command[0] == 'rls':
result = os.popen('dir').read().encode('utf-8')
self.request.sendall(result)
continue
if command[0] == '?' or recv_data[0] == 'help':
send_help = '''
?\help: Get help.
Get: Downlaod file from remote server.
Send: Send local file to remote server.
ls: List local file.
rls: List remote server file.
quit\exit: Quit the application.
'''
self.request.sendall(send_help.encode('utf-8'))
continue
if command[0] == 'send':
filename = ' '.join(command[1:-1])
totalSize = int(command[-1])
logger.info ('待接收文件%s总大小:%sKB'%(filename,totalSize))
self.request.sendall(b'ok2send')
revSize=0
logger.info ('Recieving....')
with open(filename,'wb') as f:
while 1:
recv_data = self.request.recv(BUFSIZ)
revSize =len(recv_data)
percent=str(revSize*100//totalSize) '% '
#logger.info (percent)
#if recv_data==b'send over!':
# break
f.write(recv_data)
self.request.send(percent.encode('utf-8'))
if revSize>=totalSize :
sleep(0.5)
self.request.sendall(b'File transfer successed!')
break
#self.request.sendall('\033[33;1mFile transfer successed!!!\033[0m')
logger.info('File transfer successed!')
continue
if command[0] == 'get':
filename = command[1]
if os.path.isfile(filename):
msg='ok2get' ' ' str(os.stat(filename)[6])
self.request.sendall(msg.encode('utf-8'))
if self.request.recv(BUFSIZ) == b'ok2send':
self.request.sendall(b'sending')
sleep(0.5)
file_data = open(filename,'rb')
file_tmp = file_data.read()
self.request.sendall(file_tmp)
file_data.close()
sleep(1)
self.request.sendall(b'Downloading completed!')
else:
msg='fail2get'
errInfo=' %s not found!'% filename
logger.info(errInfo)
msg =errInfo
self.request.sendall(msg.encode('utf-8'))
logger.info('%s Downloading failed!'% self.client_address[0])
continue
if command[0] == 'cd' or (command[0][0:2]=='cd' and len(command)==1):
nowPath=os.path.abspath('.')
path = ' '.join(command).replace('cd ','')
if path=='.' or recv_data == 'cd' or recv_data == 'cd.':
nowPath=os.path.abspath('.')
self.request.sendall(nowPath.encode('utf-8'))
elif path=='~' or recv_data =='cd~':
lastPath=os.path.abspath('.')
os.chdir(homePath)
nowPath=os.path.abspath('.')
self.request.sendall(nowPath.encode('utf-8'))
elif path=='-' or recv_data == 'cd-':
if 'lastPath' in locals().keys():
path=lastPath
lastPath=os.path.abspath('.')
os.chdir(path)
else:
os.chdir('.')
nowPath=os.path.abspath('.')
self.request.sendall(nowPath.encode('utf-8'))
elif path=='..' or recv_data =='cd..':
lastPath=os.path.abspath('.')
os.chdir(GetParentPath(nowPath))
nowPath=os.path.abspath('.')
self.request.sendall(nowPath.encode('utf-8'))
elif os.path.exists(path):
lastPath=os.path.abspath('.')
os.chdir(path)
nowPath=os.path.abspath('.')
self.request.sendall(nowPath.encode('utf-8'))
else:
self.request.sendall(b'No such directory!')
self.request.sendall(b'data transfer over!')
continue
if command[0]=='type' or command[0]=='cat' :
filename = recv_data.replace('type','').replace('get','').lstrip()
if os.path.isfile(filename):
try:
content = ReadFile(filename).encode('utf-8')
except:
self.request.sendall(b'Can\'t read file!')
self.request.sendall(b'data transfer over!')
continue
self.request.sendall(content)
else:
self.request.sendall(b'File not found!')
self.request.sendall(b'data transfer over!')
continue
status,result=subprocess.getstatusoutput(recv_data)
if len(result.strip())!=0:
self.request.sendall(result.encode('utf-8'))
else:
self.request.send(b'done')
self.request.sendall(b'data transfer over!')
continue
except KeyboardInterrupt:
break
except ConnectionError:
logger.error('%s\'s connection closed!!'% self.client_address[0])
break
except:
#traceback.print_exc()
logger.info('error!')
self.request.sendall(b'error!')
continue
if __name__ == '__main__':
HOST,PORT = ' ',9889
ADDR = (HOST,PORT)
BUFSIZ = 8192
try:
server = ThreadingTCPServer(ADDR,MyFtp)
server.serve_forever()
except ConnectionError:
logger.error('%s\'s connection closed!!'% self.client_address[0])
except KeyboardInterrupt:
server.shutdown()
logger.error('Forced to quit!!')
except:
pass
标签: python FTP
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明


网友评论
我要评论