Python example of a network program that implements FTP-like transfer files

Source: Internet
Author: User
Tags ftp client
This code is written on Linux and is suitable for several commands that need to be changed under Linux,windows.
1, the client input IP, port, can be connected to the server side, is required to enter a user name and password to verify.
2, using a separate module to verify the login user (limited technology, do not support client-created users), user name: ftpuser Password: userlogin
2. After successful client login verification, can I use? Or help view the commands you can use.


ftpserver.py
Copy the Code code 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] = = ' RLS ':
result = Os.popen (' ls -L./'). Read ()
Self.request.sendall (Result)
Continue
if recv_data[0] = = '? ' or recv_data[0] = = ' Help ':
Sen D_help = ' \033[32;1m
? \help:get Help.
GET:DOWNLAOD file from remote server.
Send:send local file to remote server. The
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
Copy the Code code 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 isn't 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
Copy the Code code 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: ')). St RIP ()
S.sendall (PASS)
RECV_MSG1 = S.recv (bufsiz)
If recv_msg1 = = ' Ok2login ':
print ' \033[33;1mlogin succe Ss!!! \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 I Nput = = ' 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[3 1;1myou must specified filename!! \033[0m '
Continue
elif INPUT = = ' ls ':
cmd = Os.popen (' ls-l./'). Read ()
print cmd
continue
Elif in PUT = = ' 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 (fil ename, ' 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 ()

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.