python --利用Socket多线程的FTP程序

python –利用Socket多线程的FTP程序

1.代码
服务器端代码:

root@kali:~/python/socket/ftp# pwd
/root/python/socket/ftp
root@kali:~/python/socket/ftp# ls
socket_server_ftp1.py  socket_server_ftpok.py  tab.py  tab.pyc  xwb.txt
root@kali:~/python/socket/ftp# ls -a
.  ..  socket_server_ftp1.py  socket_server_ftpok.py  tab.py  tab.pyc  xwb.txt
root@kali:~/python/socket/ftp# ls -la
总用量 20
drwxr-xr-x 2 root root 4096  716 21:03 .
drwxr-xr-x 3 root root 4096  715 10:42 ..
-rw-r--r-- 1 root root  660  715 17:43 socket_server_ftp1.py
-rw-r--r-- 1 root root 3398  716 21:00 socket_server_ftpok.py
-rw-r--r-- 1 root root    0  715 22:11 tab.py
-rw-r--r-- 1 root root  547  715 17:45 tab.pyc
-rw-r--r-- 1 root root    0  716 21:03 xwb.txt



root@kali:~/python/socket/ftp# cat socket_server_ftpok.py 
#!/usr/bin/python
# --*-- coding:utf-8 --*--

import SocketServer
import os
from time import ctime,sleep
#import socket
#服务器端IP地址192.168.72.129

HOST = ''
PORT = 21567
ADDR = (HOST,PORT)

class MyRequestHandler(SocketServer.BaseRequestHandler):
    def handle(self):#调用MyRequestHandler类必须使用handle函数
        print '...connected from :', self.client_address
        #print self.request.recv(1024)
        #self.request.send('Username')
        #----------Auth part------------------
        if self.request.recv(1024) == 'auth':
            print 'auth'
            while 1:
                self.request.send('Username')
                username = self.request.recv(1024)
                sleep(1)#可以处理验证账户延迟导致的死机
                if username == 'alex':
                    self.request.send('correct')
                    print 'Correct! Welcome!!'
                    break
                else:
                    self.request.send('incorrect')
                    continue

        def SendFromClient(filename):#服务器端发送文件函数,内置函数
            print 'start receiving data'
            f = file(filename,'wb')#二进制方式读取打开客户端刚刚发送过来的数据
            while True:#一直循环接收客户端发送过来的数据
                data = self.request.recv(4096)
                if data == 'file_send_done':break#如果收到file_send_done信息,就结束
                f.write(data)#否则把接收到的信息写入data文件中
            f.close()
            print 'file %s receive done!' % filename

        def SendToClient(filename):#服务器端接收文件函数,内置函数
            print 'start sending file to client....'
            f = file(filename,'rb')
            #while True:
            file_data = f.read()
            #if not file_data:break
            self.request.sendall(file_data)
            f.close()
            print 'file %s sent to client finished!' % filename
            sleep(0.5)
            self.request.send('file_send_to_client_done')

        #ftp()
        while True:
            try:
                re_msg = self.request.recv(1024)
                print 'get',re_msg
                if re_msg.split()[0] == 'send':
                    filename = re_msg.split()[1]
                    self.request.send('ok2send')
                    print 'ready to receive file from %s' % self.client_address[0]
                    SendFromClient(filename)#调用发送文件函数
                elif re_msg.split()[0] == 'get':
                    filename = re_msg.split()[1]
                    try:
                        os.stat(filename)
                    except OSError:
                        msg = '\033[31;1mNo file %s found on FTP server\033[0m' % filename
                        self.request.send(msg)
                        print msg
                    else:
                        self.request.send('ok2get')
                        sleep(0.5)
                        print 'ready to send file to client %s' % self.client_address[0]
                        SendToClient(filename)#调用接收文件函数
                elif re_msg == 'help' or re_msg == '?':
                    help_msg = '''\033[32;1m\nhelp\nget filename\tget file from FTP server\nsend filename\tsend file to FTP server\nls\t\tshow file list on FTP server\033[0m'''
                    self.request.send(help_msg)
                elif re_msg == 'ls':
                    print 'print dir list',re_msg
                    #file_list = os.listdir('.')
                    #convert2string = '\t'.jion(file_list)
                    file_list = os.popen('ls -lth')
                    f_list = file_list.read()
                    self.request.sendall(f_list)
                else:
                    print 'invalid instruction'
                    self.request.send('\033[31;1minvalid_instruction\033[0m')
                    print "get from %s : %s" % (self.client_address[0],re_msg)
                    #self.request.sendall('[%s] %s' % (ctime(),re_msg))
            except IndexError:
                print "%s client %s logout !" % (ctime(),self.client_address[0])
                break
try:
    tcpServ = SocketServer.ThreadingTCPServer(ADDR,MyRequestHandler)
    print 'waiting for connection........'
    tcpServ.serve_forever()
except  socket.error,e:
    print 'error happend!!'

root@kali:~/python/socket/ftp# 

客户端代码:

root@kali:~/python/socket/ftp# pwd
/root/python/socket/ftp
root@kali:~/python/socket/ftp# ls -la
总用量 36
drwxr-xr-x 2 root root 4096  716 21:02 .
drwxr-xr-x 3 root root 4096  715 09:39 ..
-rw-r--r-- 1 root root  351  715 17:46 socket_clent_ftp1.py
-rw-r--r-- 1 root root 2311  716 21:00 socket_clent_ftpok.py
-rw-r--r-- 1 root root  382  715 17:44 tab.py
-rw-r--r-- 1 root root  547  715 17:44 tab.pyc
-rw-r--r-- 1 root root  408  715 22:03 user_startup.py
-rw-r--r-- 1 root root  555  715 22:10 user_startup.pyc
-rw-r--r-- 1 root root   14  716 21:02 xwb.txt



root@kali:~/python/socket/ftp# cat socket_clent_ftpok.py 
#!/usr/bin/env python
# --*-- coding:utf-8 --*--
import tab
import user_startup
import os
from time import sleep
from socket import *

#客户端Ip地址192.168.72.130

HOST = '192.168.72.129'
PORT = 21567
BUFSIZ = 4096
ADDR = (HOST,PORT)
tcpCliSock = socket(AF_INET,SOCK_STREAM)
tcpCliSock.connect(ADDR)

tcpCliSock.send('auth')
while 1:
    #tcpCliSock.send('auth')
    if tcpCliSock.recv(BUFSIZ) == 'Username':
        print 'please input your username:'
        while 1:
            data = raw_input('Username:>').strip()
            if len(data) == 0:continue
            else:break
        tcpCliSock.send(data)
        if tcpCliSock.recv(BUFSIZ) == 'correct':
            print 'welcome'
            break
        else:
            print 'Wrong pass'
            continue

while 1:
    data = raw_input('ftp>').strip()
    if len(data) == 0:continue
    if data == 'quit':
        tcpCliSock.close()
        break
    if data == 'get' or data == 'send':
        print '\033[31;1mNo file specified,usr %s filename \033[0m' % data
        continue
    if data == 'ls':
        tcpCliSock.send(data)
        file_list = tcpCliSock.recv(8096)
        print file_list
    if data.split()[0] == 'send':
        try:
            os.stat(data.split()[1])
        except  OSError:
            print '\033[31;1mNo file %s found on localhost\033[0m' % data.split()[1]
            continue
    tcpCliSock.send(data)
    print 'send msg:', data
    #tcpCliSock.send('%s\r\n' % data)
    recv_data = tcpCliSock.recv(BUFSIZ)
    if recv_data == 'ok2send':#向服务器上传输文件
        file2send = data.split()[1]
        f = open(file2send,'rb')#打开本地文件file2send
        file_data = f.read()#把整个文件读取到内存中
        f.close()
        tcpCliSock.sendall(file_data)#sendall一次性读取的文件信息发送完成,以一条消息方式发送
        print 'file sent finished!!'
        sleep(0.5)#等待0.5秒
        tcpCliSock.send('file_sent_done')
    if recv_data == 'ok2get':#客户端发送文件到服务器
        file2get = 'test/%s' % data.split()[1]
        f = file(file2get,'wb')
        file_get_done_mark = 0
        while True:#不断给服务器发送文件
            get_data = tcpCliSock.recv(1024)
            if get_data == 'file_send_to_client_done':
                file_get_done_mark = 1
                break
            f.write(get_data)
        f.close()
        if file_get_done_mark == 1:
            print 'Download file %s from FTP server success!' % file2get
            continue
        else:
            print 'wrong'
        print 'File %s receive done!!' % filename
    else:
        #print 'invalid cmd'
        print 'FTP server :',recv_data


root@kali:~/python/socket/ftp# 

客户端导入user_start.py文件代码:

root@kali:~/python/socket/ftp# cat user_startup.py
#!/usr/bin/python
# --*-- coding:utf-8 --*--

import sys
import readline
import rlcompleter
import atexit
import os

#tab completion
readline.parse_and_bind('tab: complete')
#history file
histfile = os.path.join(os.environ['HOME'],'.pythonhistory')
try:
    readline.read_history_file(histfile)
except IOError:
    pass
    atexit.register(readline.write_history_file,histfile)

del os,histfile,readline,rlcompleter

root@kali:~/python/socket/ftp# 

2.运行情况
服务器端:

root@kali:~/python/socket/ftp# python socket_server_ftpok.py 
waiting for connection........
...connected from : ('192.168.72.130', 53177)
auth
Correct! Welcome!!
get ls
print dir list ls
get ls
print dir list ls
get ?
get ls
print dir list ls
get ls
print dir list ls
get 
Sun Jul 16 21:02:20 2017 client 192.168.72.130 logout !
...connected from : ('192.168.72.130', 53178)
auth
Correct! Welcome!!
get ls
print dir list ls
get ls
print dir list ls
get ?
get send xwb.txt
ready to receive file from 192.168.72.130
start receiving data
...connected from : ('192.168.72.130', 53181)
auth
Correct! Welcome!!
get ls
print dir list ls
get ls
print dir list ls


#运行前
root@kali:~/python/socket/ftp# ls -la
总用量 20
drwxr-xr-x 2 root root 4096  716 21:03 .
drwxr-xr-x 3 root root 4096  715 10:42 ..
-rw-r--r-- 1 root root  660  715 17:43 socket_server_ftp1.py
-rw-r--r-- 1 root root 3398  716 21:00 socket_server_ftpok.py
-rw-r--r-- 1 root root    0  715 22:11 tab.py
-rw-r--r-- 1 root root  547  715 17:45 tab.pyc
root@kali:~/python/socket/ftp# cat socket_server_ftpok.py 

#运行后
root@kali:~/python/socket/ftp# ls -la
总用量 20
drwxr-xr-x 2 root root 4096  716 21:03 .
drwxr-xr-x 3 root root 4096  715 10:42 ..
-rw-r--r-- 1 root root  660  715 17:43 socket_server_ftp1.py
-rw-r--r-- 1 root root 3398  716 21:00 socket_server_ftpok.py
-rw-r--r-- 1 root root    0  715 22:11 tab.py
-rw-r--r-- 1 root root  547  715 17:45 tab.pyc
-rw-r--r-- 1 root root    0  716 21:03 xwb.txt
root@kali:~/python/socket/ftp# cat socket_server_ftpok.py 

客户端1:

root@kali:~/python/socket/ftp# python socket_clent_ftpok.py 
please input your username:
Username:>ss
Wrong pass
please input your username:
Username:>alex
welcome
ftp>ls
总用量 12K
-rw-r--r-- 1 root root 3.4K  7月 16 21:00 socket_server_ftpok.py
-rw-r--r-- 1 root root    0  7月 15 22:11 tab.py
-rw-r--r-- 1 root root  547  7月 15 17:45 tab.pyc
-rw-r--r-- 1 root root  660  7月 15 17:43 socket_server_ftp1.py

send msg: ls
FTP server : 总用量 12K
-rw-r--r-- 1 root root 3.4K  7月 16 21:00 socket_server_ftpok.py
-rw-r--r-- 1 root root    0  7月 15 22:11 tab.py
-rw-r--r-- 1 root root  547  7月 15 17:45 tab.pyc
-rw-r--r-- 1 root root  660  7月 15 17:43 socket_server_ftp1.py

ftp>?
send msg: ?
FTP server : 
help
get filename    get file from FTP server
send filename   send file to FTP server
ls      show file list on FTP server
ftp>send xwb.txt
send msg: send xwb.txt
file sent finished!!
FTP server : ok2send
ftp>ls

客户端2:

root@kali:~/python/socket/ftp# python socket_clent_ftpok.py 
please input your username:
Username:>alex
welcome
ftp>ls
总用量 12K
-rw-r--r-- 1 root root    0  7月 16 21:03 xwb.txt
-rw-r--r-- 1 root root 3.4K  7月 16 21:00 socket_server_ftpok.py
-rw-r--r-- 1 root root    0  7月 15 22:11 tab.py
-rw-r--r-- 1 root root  547  7月 15 17:45 tab.pyc
-rw-r--r-- 1 root root  660  7月 15 17:43 socket_server_ftp1.py

send msg: ls
FTP server : 总用量 12K
-rw-r--r-- 1 root root    0  7月 16 21:03 xwb.txt
-rw-r--r-- 1 root root 3.4K  7月 16 21:00 socket_server_ftpok.py
-rw-r--r-- 1 root root    0  7月 15 22:11 tab.py
-rw-r--r-- 1 root root  547  7月 15 17:45 tab.pyc
-rw-r--r-- 1 root root  660  7月 15 17:43 socket_server_ftp1.py

ftp>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

徐为波

看着给就好了,学习写作有点累!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值