This article mainly introduces the example of a network program that implements ftp-like file transfer in python. if you need this code, you can refer to it and write it on linux. it is applicable to linux and windows, and several commands need to be changed.
1. enter the IP address and port of the client to connect to the server. the user name and password are required for verification.
2. use an independent module to authenticate the login user (the technology is limited, and the client creation user is not supported). user name: ftpuser password: userlogin
2. after the client login verification is successful, can I use? Or help to view available commands.
Ftpserver. py
The code is as follows:
#! /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] = 'Ls ':
Result = OS. popen ('ls-l./'). read ()
Self. request. sendall (result)
Continue
If recv_data [0] = '? 'Or recv_data [0] = 'help ':
Send_help = ''' \ 033 [32; 1 m
? \ 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; 1 mFile 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; 1 mDownloading complete! \ 033 [0m ')
File_data.close ()
Else:
Self. request. sendall ('fail2get ')
If self. request. recv (BUFSIZ) = 'ack ':
Self. request. sendall ('\ 033 [31; 1 m % s not found \ 033 [0m' % filename)
Except t:
Pass
If _ name _ = '_ main __':
HOST, PORT = '', 9889
ADDR = (HOST, PORT)
Bufsiz= 8192
Try:
Server = ThreadingTCPServer (ADDR, MyFtp)
Server. serve_forever ()
Except t KeyboardInterrupt:
Server. shutdown ()
Loginauth. py
The code is as follows:
#! /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
The code is as follows:
#! /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; 1 mlogin success !!! \ 033 [0m'
Break
Elif recv_msg1 = 'fail2login ':
Print '\ 033 [33; 1 mlogin failure !!! \ 033 [0m'
Continue
Else:
Continue
Except t:
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; 1 mYou must specified filename !! \ 033 [0m'
Continue
Elif INPUT = 'Ls ':
Cmd = OS. popen ('ls-l./'). read ()
Print cmd
Continue
Elif INPUT = 'Ls ':
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; 1 m % 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 ()
# Defautf-8 9889
PORT = int (raw_input ('server PORT :'))
ADDR = (HOST, PORT)
Bufsiz= 8192
S = socket (AF_INET, SOCK_STREAM)
Try:
S. connect (ADDR)
Except t:
Pass
If auth () = 'error ':
Print 'connection refused .'
Else:
Switch ()