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

此代码在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()

(0)

相关推荐

  • python从ftp下载数据保存实例

    <hadoop权威指南>的天气数据可以在ftp://ftp3.ncdc.noaa.gov/pub/data/noaa下载,在网上看到这个数据好开心,打开ftp发现个问题,呀呀,这么多文件啊,我一个个去点另存为,得点到啥时候啊,迅雷应该有批量下载,只是我没找到,估计是我浏览器把迅雷禁掉了,干脆自己用python写一个实现下载好了,网上早了一下,发现很简单啊 复制代码 代码如下: #!/usr/bin/python#-*- coding: utf-8 -*- from ftplib import

  • python3实现ftp服务功能(客户端)

    本文实例为大家分享了python3实现ftp服务功能的具体代码,供大家参考,具体内容如下 客户端 main代码: #Author by Andy #_*_ coding:utf-8 _*_ ''' This program is used to create a ftp client ''' import socket,os,json,time,hashlib,sys class Ftp_client(object): def __init__(self): self.client = sock

  • 通过python下载FTP上的文件夹的实现代码

    复制代码 代码如下: # -*- encoding: utf8 -*-import osimport sysimport ftplibclass FTPSync(object):    def __init__(self):        self.conn = ftplib.FTP('10.22.33.46', 'user', 'pass')        self.conn.cwd('/')        # 远端FTP目录        os.chdir('/data/')       

  • python实现的简单FTP上传下载文件实例

    本文实例讲述了python实现的简单FTP上传下载文件的方法.分享给大家供大家参考.具体如下: python本身自带一个FTP模块,可以实现上传下载的函数功能. #!/usr/bin/env python # -*- coding: utf-8 -*- from ftplib import FTP def ftp_up(filename = "20120904.rar"): ftp=FTP() ftp.set_debuglevel(2) #打开调试级别2,显示详细信息;0为关闭调试信息

  • python实现从ftp服务器下载文件的方法

    本文实例讲述了python实现从ftp服务器下载文件的方法.分享给大家供大家参考.具体实现方法如下: import ftplib ftp = ftblib.FTP("ftp.yourServer.com") ftp.login("username","password") filename = "index.html" ftp.storlines("STOR "+filename,open(filename

  • 400多行Python代码实现了一个FTP服务器

    Python版本 实现了比之前的xxftp更多更完善的功能 1.继续支持多用户 2.继续支持虚拟目录 3.增加支持用户根目录以及映射虚拟目录的权限设置 4.增加支持限制用户根目录或者虚拟目录的空间大小 xxftp的特点 1.开源.跨平台 2.简单.易用 3.不需要数据库 4.可扩展性超强 5.你可以免费使用xxftp假设自己的私人FTP服务器 测试地址 ftp://xiaoxia.org 匿名帐号可以使用! 匿名根目录只读,映射了一个虚拟目录,可以上传文件但不允许更改! 使用方法 跟之前用C语言

  • python连接远程ftp服务器并列出目录下文件的方法

    本文实例讲述了python连接远程ftp服务器并列出目录下文件的方法.分享给大家供大家参考.具体如下: 这段python代码用到了pysftp模块,使用sftp协议,对数据进行加密传输 import pysftp srv = pysftp.Connection(host="your_FTP_server", username="your_username",password="your_password") # Get the directory

  • python3实现ftp服务功能(服务端 For Linux)

    本文实例为大家分享了python3实现ftp服务功能的具体代码,供大家参考,具体内容如下 功能介绍: 可执行的命令: ls pwd cd put rm get mkdir 1.用户加密认证 2.允许多用户同时登陆 3.每个用户有自己的家目录,且只可以访问自己的家目录 4.运行在自己家目录下随意切换目录 5.允许上传下载文件,且文件一致 6.传输过程中显示进度条 server main 代码: # Author by Andy # _*_ coding:utf-8 _*_ import os, s

  • python实现支持目录FTP上传下载文件的方法

    本文实例讲述了python实现支持目录FTP上传下载文件的方法.分享给大家供大家参考.具体如下: 该程序支持ftp上传下载文件和目录.适用于windows和linux平台. #!/usr/bin/env python # -*- coding: utf-8 -*- import ftplib import os import sys class FTPSync(object): conn = ftplib.FTP() def __init__(self,host,port=21): self.c

  • python实现ftp客户端示例分享

    复制代码 代码如下: #!/usr/bin/python#coding:utf-8#write:JACK#info:ftp exampleimport ftplib, socket, osfrom time import sleep, ctime def LoginFtp(self):        ftps = ftplib.FTP()        ftps.connect(self.host,self.port)        ftps.login(self.name,self.passw

随机推荐