国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python實現類似ftp傳輸文件的網絡程序示例

2019-11-25 18:27:31
字體:
來源:轉載
供稿:網友

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 南宫市| 怀安县| 扶余县| 蒙城县| 淮南市| 昌乐县| 松江区| 麻江县| 宣武区| 阿尔山市| 甘孜县| 贺兰县| 江西省| 曲周县| 轮台县| 丹棱县| 江西省| 合肥市| 加查县| 嘉兴市| 林周县| 梅河口市| 徐汇区| 大悟县| 普安县| 岚皋县| 三原县| 北流市| 内黄县| 遂川县| 云梦县| 廊坊市| 泾源县| 奉贤区| 屏山县| 独山县| 潜江市| 左权县| 东海县| 彩票| 洛南县|