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多线程编程中的join函数使用心得
Sep 02 Python
Python列表list数组array用法实例解析
Oct 28 Python
Python实现统计英文单词个数及字符串分割代码
May 28 Python
Python简单实现enum功能的方法
Apr 25 Python
浅谈Python 集合(set)类型的操作——并交差
Jun 30 Python
使用Python编写一个最基础的代码解释器的要点解析
Jul 12 Python
python3的输入方式及多组输入方法
Oct 17 Python
Python matplotlib模块及柱状图用法解析
Aug 10 Python
python 自定义异常和主动抛出异常(raise)的操作
Dec 11 Python
Python 实现集合Set的示例
Dec 21 Python
K近邻法(KNN)相关知识总结以及如何用python实现
Jan 28 Python
python 高阶函数简单介绍
Feb 19 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随机数生成代码与使用实例分析
2011/04/08 PHP
对PHP新手的一些建议(PHP学习经验总结)
2014/08/20 PHP
利用php输出不同的心形图案
2016/04/22 PHP
PHP实现可精确验证身份证号码的工具类示例
2018/05/31 PHP
jQuery之浮动窗口实现代码(两种方法)
2010/09/08 Javascript
javascript Array对象基础知识小结
2010/11/16 Javascript
基于JQuery实现异步刷新的代码(转载)
2011/03/29 Javascript
关于js日期转化为毫秒数“节省20%的效率和和节省9个字符“问题
2012/03/01 Javascript
JS时间选择器 兼容IE6,7,8,9
2012/06/26 Javascript
javascript面向对象入门基础详细介绍
2012/09/05 Javascript
jQuery之日期选择器的深入解析
2013/06/19 Javascript
用jquery实现动画跳到顶部和底部(这个比较简单)
2014/09/01 Javascript
JavaScript function函数种类详解
2016/02/22 Javascript
JavaScript 正则表达式中global模式的特性
2016/02/25 Javascript
jQuery动态生成Bootstrap表格
2016/11/01 Javascript
微信小程序与php 实现微信支付的简单实例
2017/06/23 Javascript
mpvue全局引入sass文件的方法步骤
2019/03/06 Javascript
为react组件库添加typescript类型提示的方法
2020/06/15 Javascript
python生成验证码图片代码分享
2016/01/28 Python
正确理解python中的关键字“with”与上下文管理器
2017/04/21 Python
python3.6使用pickle序列化class的方法
2018/10/22 Python
详细介绍Python进度条tqdm的使用
2019/07/31 Python
浅谈Python_Openpyxl使用(最全总结)
2019/09/05 Python
TensorFlow tensor的拼接实例
2020/01/19 Python
python 生成正态分布数据,并绘图和解析
2020/12/21 Python
Python实现钉钉/企业微信自动打卡的示例代码
2021/02/02 Python
Links of London官方网站:英国标志性的珠宝品牌
2017/04/09 全球购物
澳大利亚网上玩具商店:Mr Toys Toyworld
2018/03/25 全球购物
Seavenger官网:潜水服、浮潜、靴子和袜子
2020/03/05 全球购物
2014年超市员工工作总结
2014/11/18 职场文书
班主任高考寄语
2015/02/26 职场文书
保险内勤岗位职责
2015/04/13 职场文书
小学安全工作总结2015
2015/05/18 职场文书
2019优秀干部竞聘演讲稿范文!
2019/07/02 职场文书
商业计划书之服装
2019/09/09 职场文书
MySQL聚簇索引和非聚簇索引的区别详情
2022/06/14 MySQL