python实现类似ftp传输文件的网络程序示例


Posted in Python onApril 08, 2014

此代码在linux上编写,适用于linux,windows下需要更改几个命令。
1、客户端输入IP,端口,可服务器端进行连接,被要求输入用户名和密码进行验证。
2、使用独立的模块来验证登录用户(技术有限,不支持客户端创建用户),用户名:ftpuser  密码:userlogin
2、客户端登录验证成功后,可使用?或者help查看可使用的命令。

ftpserver.py

#!/usr/bin/env python
#-*- coding:utf-8
"Program for ftp server"
from SocketServer import *
from time import *
import os
import loginauth
 
class MyFtp(StreamRequestHandler):
    def handle(self):
        try:
            while True:
                sleep(0.5)
                self.request.sendall('auth')
                name = self.request.recv(BUFSIZ)
                sleep(0.5)
                self.request.sendall('pauth')
                password = self.request.recv(BUFSIZ)
                print name,password
                auth_result = loginauth.user_create(name,password)
                print auth_result
                if auth_result == 0:
                    self.request.sendall('ok2login')
                    break
                elif auth_result == 1:
                    self.request.sendall('fail2login')
                    continue
            while True:
                recv_data = self.request.recv(BUFSIZ).split()
                if recv_data[0] == 'rls':
                    result = os.popen('ls -l ./').read()
                    self.request.sendall(result)
                    continue
                if recv_data[0] == '?' or recv_data[0] == 'help':
                    send_help = '''\033[32;1m
                                ?\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.
                                \033[0m'''
                    self.request.sendall(send_help)
                    continue
                if recv_data[0] == 'send':
                    filename = recv_data[1]
                    self.request.sendall('ok2send')
                    recv_data = self.request.recv(BUFSIZ)
                    file2w = open(filename,'wb')
                    file2w.write(recv_data)
                    file2w.flush()
                    file2w.close()
                    self.request.sendall('\033[33;1mFile transfer successed!!!\033[0m')
                    continue
                if recv_data[0] == 'get':
                    filename = recv_data[1]
                    if os.path.isfile(filename):
                        self.request.sendall('ok2get')
                        if self.request.recv(BUFSIZ) == 'ok2send':
                            self.request.sendall('sending')
                            sleep(0.5)
                            file_data = open(filename,'rb')
                            file_tmp = file_data.read()
                            self.request.sendall(file_tmp)
                            sleep(1)
                            self.request.sendall('\033[33;1mDownloading complete!\033[0m')
                            file_data.close()
                    else:
                        self.request.sendall('fail2get')
                        if self.request.recv(BUFSIZ) == 'ack':
                            self.request.sendall('\033[31;1m%s not found\033[0m'% filename)
        except :
            pass

if __name__ == '__main__':
    HOST,PORT = '',9889
    ADDR = (HOST,PORT)
    BUFSIZ = 8192
    try:
        server = ThreadingTCPServer(ADDR,MyFtp)
        server.serve_forever()
    except KeyboardInterrupt:
        server.shutdown()

loginauth.py

#!/usr/bin/env python
#-*- coding:utf-8
#Filename:userlogin.py
"Program for userlogin"
import sys,time
import cPickle as pickle
#If it's your first running this program,use USERDB = {}
#If it is not your first running this program,use USERDB = pickle.load(open('userdb','rb'))
USERDB = pickle.load(open('userdb','rb'))
#USERDB = {}
class userdb(object):
    def __init__(self,username,password,time):
        self.username = username
        self.passwd = password
        self.time = time
    def save_user(self):
        USERDB[self.username] = [self.passwd,self.time]
        pickle.dump(USERDB,open('userdb','wb'),True)
    def update_db(self):
        pass
 
def user_create(NAME,PASSWD = ''):
    if NAME in USERDB:
        if PASSWD == USERDB[NAME][0]:
            p = userdb(NAME,PASSWD,time.time())
            p.save_user()
            return 0
        else:
            return 1
    else:
        #p = userdb(NAME,PASSWD,time.time())
        #p.save_user()
        return 1
if __name__ == '__main__':
    user_create(name,password)

ftpclient.py

#!/usr/bin/env python
#-*- coding:utf-8

"Program for ftp client."
from socket import *
from time import sleep
import os

def auth():
    while 1:
        try:
            recv_msg = s.recv(BUFSIZ)
            if recv_msg == 'auth':
                USER = str(raw_input('Please input your username: ')).strip()
                s.sendall(USER)
                if s.recv(BUFSIZ) == 'pauth':
                    PASS = str(raw_input('Please input your password: ')).strip()
                    s.sendall(PASS)
                    recv_msg1 = s.recv(BUFSIZ)
                    if recv_msg1 == 'ok2login':
                        print '\033[33;1mlogin success!!!\033[0m'
                        break
                    elif  recv_msg1 == 'fail2login':
                        print '\033[33;1mlogin failure!!!\033[0m'
                        continue
                    else:
                        continue
        except:
            return 'error'
def switch():
    while True:
        INPUT = str(raw_input('ftp> ')).strip()
        if len(INPUT) == 0:continue
        elif INPUT == 'quit' or INPUT == 'exit':
            s.close()
            break
        elif INPUT == '?' or INPUT == 'help':
            s.send(INPUT)
            recv_data = s.recv(BUFSIZ)
            print recv_data
            continue
        elif INPUT == 'get' or INPUT == 'send':
            print '\033[31;1mYou must specified filename!!\033[0m'
            continue
        elif INPUT == 'ls':
            cmd = os.popen('ls -l ./').read()
            print cmd
            continue
        elif INPUT == 'rls':
            s.send(INPUT)
            recv_data = s.recv(BUFSIZ)
            print recv_data
            continue
        elif INPUT.split()[0] == 'send':
            filename = INPUT.split()[1]
            if os.path.isfile(filename):
                print 'Sending %s......'% filename
                s.sendall(INPUT)
                re_data = s.recv(BUFSIZ)
                if re_data == 'ok2send':
                    file_data = open(filename,'rb')
                    file_tmp = file_data.read()
                    file_data.close()
                    s.sendall(file_tmp)
                    sleep(0.5)
                    recv_data = s.recv(BUFSIZ)
                    print recv_data
                    continue
                else:continue
            else:
                print '\033[31;1m%s not found!\033[0m'% filename
        elif INPUT.split()[0] == 'get':
            filename = INPUT.split()[1]
            s.sendall(INPUT)
            msg1 = s.recv(BUFSIZ)
            if msg1 == 'ok2get':
                s.sendall('ok2send')
                msg2 = s.recv(BUFSIZ)
                if msg2 == 'sending':
                    file_data = s.recv(BUFSIZ)
                    file2w = open(filename,'wb')
                    file2w.write(file_data)
                    file2w.flush()
                    file2w.close()
                    msg3 = s.recv(BUFSIZ)
                    print msg3
                    continue
            elif msg1 == 'fail2get':
                s.send('ack')
                msg4 = s.recv(BUFSIZ)
                print msg4
                continue
        else:
            continue

if __name__ == '__main__':
    #Default 127.0.0.1
    HOST = str(raw_input('Server IP: ')).strip()
    #Defautl 9889
    PORT = int(raw_input('Server PORT: '))
    ADDR = (HOST,PORT)
    BUFSIZ = 8192
    s = socket(AF_INET,SOCK_STREAM)
    try:
        s.connect(ADDR)
    except :
        pass
    if auth() == 'error':
        print 'Connection refused.'
    else:
        switch()
Python 相关文章推荐
python 基础学习第二弹 类属性和实例属性
Aug 27 Python
pygame学习笔记(3):运动速率、时间、事件、文字
Apr 15 Python
python中base64加密解密方法实例分析
May 16 Python
为Python的Tornado框架配置使用Jinja2模板引擎的方法
Jun 30 Python
python简单实现获取当前时间
Aug 27 Python
python3实现公众号每日定时发送日报和图片
Feb 24 Python
python实现顺序表的简单代码
Sep 28 Python
python利用Tesseract识别验证码的方法示例
Jan 21 Python
详解Django将秒转换为xx天xx时xx分
Sep 27 Python
基于keras输出中间层结果的2种实现方式
Jan 24 Python
Python 分布式缓存之Reids数据类型操作详解
Jun 24 Python
正确的理解和使用Django信号(Signals)
Apr 14 Python
Python collections模块实例讲解
Apr 07 #Python
python操作xml文件示例
Apr 07 #Python
python生成随机验证码(中文验证码)示例
Apr 03 #Python
python读取html中指定元素生成excle文件示例
Apr 03 #Python
python实现zencart产品数据导入到magento(python导入数据)
Apr 03 #Python
python模拟登陆阿里妈妈生成商品推广链接
Apr 03 #Python
python多线程抓取天涯帖子内容示例
Apr 03 #Python
You might like
PHP 类型转换函数intval
2009/06/20 PHP
判断Keep-Alive模式的HTTP请求的结束的实现代码
2011/08/06 PHP
解析php中的fopen()函数用打开文件模式说明
2013/06/20 PHP
php获取远程文件内容的函数
2015/11/02 PHP
PHP使用GD库制作验证码的方法(点击验证码或看不清会刷新验证码)
2017/08/15 PHP
laravel框架实现后台登录、退出功能示例
2019/10/31 PHP
javascript prototype,executing,context,closure
2008/12/24 Javascript
js限制文本框为整数和货币的函数代码
2010/10/13 Javascript
JavaScript中使用构造器创建对象无需new的情况说明
2012/03/01 Javascript
探索Emberjs制作一个简单的Todo应用
2012/11/07 Javascript
jquery 单引号和双引号的区别及使用注意
2013/07/31 Javascript
Javascript中查找不以XX字符结尾的单词示例代码
2013/10/15 Javascript
JS中window.open全屏命令解析及使用示例
2013/12/11 Javascript
javascript中传统事件与现代事件
2015/06/23 Javascript
JS实现自动切换文字的导航效果代码
2015/08/27 Javascript
分享有关jQuery中animate、slide、fade等动画的连续触发、滞后反复执行的bug
2016/01/10 Javascript
JavaScript兼容浏览器FF/IE技巧
2016/08/14 Javascript
AngularJS应用开发思维之依赖注入3
2016/08/19 Javascript
jquery引入外部CDN 加载失败则引入本地jq库
2018/05/23 jQuery
webpack常用配置总览(小结)
2019/11/18 Javascript
javascript设计模式之迭代器模式
2020/01/30 Javascript
ESLint 是如何检查 .vue 文件的
2020/11/30 Vue.js
pymongo给mongodb创建索引的简单实现方法
2015/05/06 Python
Python cx_freeze打包工具处理问题思路及解决办法
2016/02/13 Python
Python利用matplotlib生成图片背景及图例透明的效果
2017/04/27 Python
python实现excel读写数据
2021/03/02 Python
python jenkins 打包构建代码的示例代码
2019/11/29 Python
计算机应用职专应届生求职信
2013/11/12 职场文书
优秀老员工获奖感言
2014/02/15 职场文书
企业厂务公开实施方案
2014/03/26 职场文书
校庆标语集锦
2014/06/25 职场文书
党员干部形式主义个人整改措施
2014/09/17 职场文书
2015年公司后勤管理工作总结
2015/05/13 职场文书
浅谈react useEffect闭包的坑
2021/06/08 Javascript
Python实现单例模式的5种方法
2021/06/15 Python
IDEA中sout快捷键无效问题的解决方法
2022/07/23 Java/Android