当前位置:  编程技术>python

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

    来源: 互联网  发布时间:2014-10-04

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

此代码在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 = '''33[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.
                                quitexit:  Quit the application.
                                33[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('33[33;1mFile transfer successed!!!33[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('33[33;1mDownloading complete!33[0m')
                            file_data.close()

                    else:
                        self.request.sendall('fail2get')
                        if self.request.recv(BUFSIZ) == 'ack':
                            self.request.sendall('33[31;1m%s not found33[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 '33[33;1mlogin success!!!33[0m'
                        break
                    elif  recv_msg1 == 'fail2login':
                        print '33[33;1mlogin failure!!!33[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 '33[31;1mYou must specified filename!!33[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 '33[31;1m%s not found!33[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读取csv文件示例(python操作csv)
  • python下xml解析库lxml最新版下载安装以及代码示例
  • python基础教程之python消息摘要算法使用示例
  • 数据结构:图(有向图,无向图),在Python中的表示和实现代码示例
  • python实现绘制树枝简单示例
  • 使用python删除nginx缓存文件示例(python文件操作)
  • python学习手册中的python多态示例代码
  • python调用windows api锁定计算机示例
  • python代码制作configure文件示例
  • python使用循环实现批量创建文件夹示例
  • python采用requests库模拟登录和抓取数据的简单示例
  • Python数组条件过滤filter函数使用示例
  • python获得图片base64编码示例
  • Python的print用法示例
  • 基于Python的Html/xml解析库Beautiful Soup 4.2.1发布 iis7站长之家
  • Python pass 语句使用示例
  • python getopt 参数处理小示例
  • python的urllib模块显示下载进度示例
  • python list转dict示例分享
  • python求素数示例分享
  • videocapture库制作python视频高速传输程序
  • python实现的一个p2p文件传输实例
  •  
    本站(WWW.)旨在分享和传播互联网科技相关的资讯和技术,将尽最大努力为读者提供更好的信息聚合和浏览方式。
    本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。












  • 相关文章推荐
  • Python中类似printf的字符串格式化详解
  • Python GUI编程:tkinter实现一个窗口并居中代码
  • 让python同时兼容python2和python3的8个技巧分享
  • Python不使用print而直接输出二进制字符串
  • 使用setup.py安装python包和卸载python包的方法
  • Python中实现json字符串和dict类型的互转
  • 不小心把linux自带的python卸载了,导致安装一个依赖原python的软件不能安装,请问该怎么办?
  • python异常信息堆栈输出到日志文件
  • Python开发者社区整站源码 Pythoner
  • python下用os.execl执行centos下的系统时间同步命令ntpdate
  • 新手该如何学python怎么学好python?
  • Python namedtuple对象json序列化/反序列化及对象恢复
  • 请教:system("C:\python2.4\python.exe C:\aa.py");该语句有何错误?为什么运行界面一闪就消失了并且没有运行完,请给出正确语句!
  • Python异常模块traceback用法举例
  • python版本的问题
  • python之平台独立的调试工具winpdb介绍
  • Mac OS X10.9安装的Python2.7升级Python3.3步骤详解
  • 基于Python的Html/xml解析库Beautiful Soup 4.2.1发布
  • python安装的问题
  • 测试Python内部类型及type和isinstance用法区别
  • 如何运行Python程序的方法
  • Python3中内置类型bytes和str用法及byte和string之间各种编码转换
  • 明明安装了python却提示找不到!!


  • 站内导航:


    特别声明:169IT网站部分信息来自互联网,如果侵犯您的权利,请及时告知,本站将立即删除!

    ©2012-2021,,E-mail:www_#163.com(请将#改为@)

    浙ICP备11055608号-3