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抓取网页图片并放到指定文件夹
Apr 24 Python
python进阶教程之动态类型详解
Aug 30 Python
用Python编写一个每天都在系统下新建一个文件夹的脚本
May 04 Python
在Python中操作字符串之rstrip()方法的使用
May 19 Python
Python编程实现删除VC临时文件及Debug目录的方法
Mar 22 Python
python实现BackPropagation算法
Dec 14 Python
对python中的logger模块全面讲解
Apr 28 Python
python 将数据保存为excel的xls格式(实例讲解)
May 03 Python
Python rstrip()方法实例详解
Nov 11 Python
django框架使用方法详解
Jul 18 Python
使用python分析统计自己微信朋友的信息
Jul 19 Python
django序列化serializers过程解析
Dec 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性能的21种方法介绍
2013/06/25 PHP
PHP判断变量是否为0的方法
2014/02/08 PHP
详谈php中 strtr 和 str_replace 的效率问题
2017/05/14 PHP
Yii2.0建立公共方法简单示例
2019/01/29 PHP
javascript 面向对象编程基础:封装
2009/08/21 Javascript
Jquery操作下拉框(DropDownList)实现取值赋值
2013/08/13 Javascript
JavaScript实现拖拽网页内元素的方法
2015/04/15 Javascript
JavaScript中reduce()方法的使用详解
2015/06/09 Javascript
AngularJS 路由详解和简单实例
2016/07/28 Javascript
关于Vue的路由权限管理的示例代码
2018/03/06 Javascript
JavaScript 监听组合按键思路及代码实现
2020/07/28 Javascript
对vue生命周期的深入理解
2020/12/03 Vue.js
[06:07]DOTA2-DPC中国联赛3月5日Recap集锦
2021/03/11 DOTA
python del()函数用法
2013/03/24 Python
Python基于checksum计算文件是否相同的方法
2015/07/09 Python
Python字符串格式化输出方法分析
2016/04/13 Python
Python实现的拟合二元一次函数功能示例【基于scipy模块】
2018/05/15 Python
Python多进程与服务器并发原理及用法实例分析
2018/08/21 Python
Python直接赋值、浅拷贝与深度拷贝实例分析
2019/06/18 Python
PyQt5响应回车事件的方法
2019/06/25 Python
python 控制Asterisk AMI接口外呼电话的例子
2019/08/08 Python
Python判断变量是否是None写法代码实例
2020/10/09 Python
手把手教你用Django执行原生SQL的方法
2021/02/18 Python
matplotlib部件之套索Lasso的使用
2021/02/24 Python
纯CSS实现的大小渐变、渐远效果
2014/04/15 HTML / CSS
印度购物网站:TATA CLiQ
2017/11/23 全球购物
英国珠宝钟表和家居礼品精品店:David Shuttle
2018/02/24 全球购物
Nike比利时官网:Nike.com (BE)
2019/02/07 全球购物
经验丰富大学生村干部自我鉴定
2014/01/22 职场文书
疾病捐款倡议书
2014/05/13 职场文书
2014年廉洁自律承诺书
2014/05/26 职场文书
如何写观后感
2015/06/19 职场文书
2015年政治教研组工作总结
2015/07/22 职场文书
2016教师党员学习心得体会
2016/01/21 职场文书
奥特曼十大神器:奥特手镯在榜,第一是贝利亚的神器
2022/03/18 日漫
Win11 22H2 2022怎么更新? 获得Win1122H22022版本升级技巧
2022/09/23 数码科技