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爬虫抓取暴走漫画上gif图片的实例分享
Apr 20 Python
深入理解python中的闭包和装饰器
Jun 12 Python
pandas.dataframe中根据条件获取元素所在的位置方法(索引)
Jun 07 Python
python实现textrank关键词提取
Jun 22 Python
python实现将多个文件分配到多个文件夹的方法
Jan 07 Python
Python计算时间间隔(精确到微妙)的代码实例
Feb 26 Python
浅析Python与Mongodb数据库之间的操作方法
Jul 01 Python
Python搭建代理IP池实现接口设置与整体调度
Oct 27 Python
windows中安装Python3.8.0的实现方法
Nov 19 Python
python PIL/cv2/base64相互转换实例
Jan 09 Python
python yield和Generator函数用法详解
Feb 10 Python
python -v 报错问题的解决方法
Sep 15 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
js限制checkbox勾选的个数以及php获取多个checkbbox的方法深入解析
2013/07/18 PHP
smarty中js的调用方法示例
2014/10/27 PHP
Symfony学习十分钟入门经典教程
2016/02/03 PHP
thinkphp3.2中实现phpexcel导出带生成图片示例
2017/02/14 PHP
PHP convert_cyr_string()函数讲解
2019/02/13 PHP
详解将数据从Laravel传送到vue的四种方式
2019/10/16 PHP
判断脚本加载是否完成的方法
2009/05/26 Javascript
仿猪八戒网左下角的文字滚动效果
2011/10/28 Javascript
Document:getElementsByName()使用方法及示例
2013/10/28 Javascript
Node.js中child_process实现多进程
2015/02/03 Javascript
js jquery获取当前元素的兄弟级 上一个 下一个元素
2015/09/01 Javascript
Javascript之String对象详解
2016/06/08 Javascript
Jquery Easyui对话框组件Dialog使用详解(14)
2016/12/19 Javascript
angularjs实现分页和搜索功能
2018/01/03 Javascript
让网站自动生成章节目录索引的多个js代码
2018/01/07 Javascript
使用Vue.js和Element-UI做一个简单登录页面的实例
2018/02/23 Javascript
node.js博客项目开发手记
2018/03/16 Javascript
微信小程序实现日历效果
2018/12/28 Javascript
详解使用webpack+electron+reactJs开发windows桌面应用
2019/02/01 Javascript
python列表的常用操作方法小结
2016/05/21 Python
python实现简单购物商城
2016/05/21 Python
python 排序算法总结及实例详解
2016/09/28 Python
利用Django内置的认证视图实现用户密码重置功能详解
2017/11/24 Python
python实现图片文件批量重命名
2020/03/23 Python
使用django-guardian实现django-admin的行级权限控制的方法
2018/10/30 Python
在Python中append以及extend返回None的例子
2019/07/20 Python
Python 序列化和反序列化库 MarshMallow 的用法实例代码
2020/02/25 Python
python库skimage给灰度图像染色的方法示例
2020/04/27 Python
Bally澳大利亚官网:瑞士奢侈品牌
2018/11/01 全球购物
恶意软件的定义
2014/11/12 面试题
自我鉴定范文200字
2013/10/02 职场文书
护士自我鉴定
2013/10/23 职场文书
个人租房协议书
2014/04/09 职场文书
中央空调节能方案
2014/06/15 职场文书
大学生团支书竞选稿
2015/11/21 职场文书
利用Python判断整数是否是回文数的3种方法总结
2021/07/07 Python