python socket 进行文件上传下载

!/bin/python

#coding:utf-8
import SocketServer
import os
import datetime
import MySQLdb
class mysql:
def init(self):
self.connect = MySQLdb.connect(
host = ‘192.168.221.203‘,
user = ‘hall‘,
passwd = ‘520157‘,
port = 3306,
db = ‘info‘,
charset = ‘utf8‘
)
def mysql_create_table_info(self):
cursor = self.connect.cursor()
sql = """create table if not exists info(
action char(20),
actin_time varchar(40),
file_size varchar(20),
file_name varchar(40),
operation_user char(20)
)"""
cursor.execute(sql)
cursor.close()
self.connect.commit()
self.connect.close()
def mysql_create_table_user(self):
cursor = self.connect.cursor()
sql_user = """create table if not exists user(
user varchar(20),
passwd varchar(40)
)"""
cursor.execute(sql_user)
data = """insert into user values(
"hall",
"hall"),
("hexulin",
"hexulin")"""
cursor.execute(data)
cursor.close()
self.connect.commit()
self.connect.close()

class server(SocketServer.BaseRequestHandler,mysql):
def handle(self):
self.request
self.client_address
print "%s:%s is connecting....."%self.client_address
recv = self.request.recv(1024)
print recv
self.request.send("已经建立连接")
recv = self.request.recv(1024)
print recv
operation = recv.split(‘:‘)[1]
if operation == "put":
self.file_name,self.file_size = self.request.recv(1024).split(‘|‘)
self.request.send("一切准备就绪")
recv_size = 0
time_put = datetime.datetime.now()
file_path = [‘/root/‘,self.file_name]
file_path = ‘‘.join(file_path)
f = open(file_path,‘wb‘)
while recv_size != int(self.file_size):
if int(self.file_size) - recv_size > 1024:
rdata = self.request.recv(1024)
recv_size += len(rdata)
else:
rdata = self.request.recv(int(self.file_size) - recv_size)
recv_size = int(self.file_size)
f.write(rdata)
f.close()
print "文件已经保存完毕...."
connect = MySQLdb.connect(
host = ‘192.168.221.203‘,
user = ‘hall‘,
passwd = ‘520157‘,
port = 3306,
db = ‘info‘,
charset = ‘utf8‘
)
value = [operation,time_put,self.file_size,self.file_name,"hall"]

        cursor = connect.cursor()
                    data = """insert into info values(
                            %s,
                            %s,
                            %s,
                            %s,
            %s)"""
                    cursor.execute(data,value)
                    cursor.close()
                    connect.commit()
                    connect.close()

    else:
        file_path = self.request.recv(1024)
                file_name = os.path.basename(file_path)
                file_size = os.stat(file_path).st_size
                self.request.send(file_name + ‘|‘ + str(file_size))
                recv = self.request.recv(1024)
                print recv
                send_size = 0
        time_get = datetime.datetime.now()
                f = open(file_path,‘rb‘)
                while True:
                        file_data = f.read(1024)
                        if not file_data:
                                break
                        self.request.send(file_data)
                f.close()
        print "文件已经传输完毕..."
        connect = MySQLdb.connect(
                host = ‘192.168.221.203‘,
                user = ‘hall‘,
                passwd = ‘520157‘,
                port = 3306,
                db = ‘info‘,
                charset = ‘utf8‘
                )
        value = [operation,time_get,file_size,file_name,"hall"]
        cursor = connect.cursor()
                    data = """insert into info values(
                            %s,
                            %s,
                            %s,
                            %s,
            %s)"""
                    cursor.execute(data,value)
                    cursor.close()
                    connect.commit()
                    connect.close()

class insert_mysql:
def mysql_info(self):
connect = MySQLdb.connect(
host = ‘192.168.221.203‘,
user = ‘hall‘,
passwd = ‘520157‘,
port = 3306,
db = ‘info‘,
charset = ‘utf8‘
)

            cursor = connect.cursor()
            data = """insert into info values(
                   operation,
                   time),
                   self.file_size,
                   self.file_name)"""
            cursor.execute(data)
            cursor.close()
            connect.commit()
            connect.close()

if name == ‘main‘:
server = SocketServer.ThreadingTCPServer((‘192.168.221.203‘,8888),server)
server.serve_forever()

客户端
#!/bin/python
#coding:utf-8
import socket
import os

sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.connect((‘192.168.221.203‘,8888))
sock.send("我要连接你进行文件传输........")
recv = sock.recv(1024)
print recv
operation = raw_input("please input your choice Usage: put or get:")
sock.send("我要进行的操作是:%s"%operation)
if operation == "put":
file_path = raw_input("please input your input_file_path:")
file_name = os.path.basename(file_path)
file_size = os.stat(file_path).st_size
print file_size
sock.send(file_name + ‘|‘ + str(file_size))
print sock.recv(1024)
f = open(file_path,‘rb‘)
while True:
file_data = f.read(1024)
if not file_data:
break
sock.send(file_data)
f.close()
print "上传文件完毕....."
else:
file_path = raw_input("please input your get_file_path:")
sock.send(file_path)
file_name,file_size = sock.recv(1024).split(‘|‘)
get_file_path = [‘/root/‘,file_name]
get_file_path = ‘‘.join(get_file_path)
sock.send("可以开始发送,准备就绪")
recv_size = 0
f = open(get_file_path,‘wb‘)
while not int(file_size) == recv_size:
if int(int(file_size) - recv_size) > 1024:
rdata = sock.recv(1024)
recv_size += len(rdata)
else:
rdata = sock.recv(int(file_size) - recv_size)
recv_size = int(file_size)
f.write(rdata)
f.close()
print "文件下载完毕....."
sock.close()

原文地址:http://blog.51cto.com/13945009/2166121

时间: 2024-10-11 14:24:28

python socket 进行文件上传下载的相关文章

300行python代码的轻量级HTTPServer实现文件上传下载

最近,利用一下空余的时间对以前的Python知识进行了巩固和复习,便闲来无事写了一个轻量级的HTTPServer来实现文件上传下载,不废话,直接上代码: #!/usr/bin/env python # -*- coding: utf-8 -*- __version__ = "0.1" __all__ = ["SimpleHTTPRequestHandler"] __author__ = "kumikoda" __home_page__ = &qu

python之实现ftp上传下载代码(含错误处理)

# -*- coding: utf-8 -*- #python 27 #xiaodeng #python之实现ftp上传下载代码(含错误处理) #http://www.cnblogs.com/kaituorensheng/p/4480512.html#_label2 import ftplib import socket import os def ftpconnect(ftp_info): try: ftp = ftplib.FTP(ftp_info[0]) except (socket.er

3Python全栈之路系列之基于socket实现文件上传

Python全栈之路系列之基于socket实现文件上传 发布时间:2017年3月16日 00:04 浏览(106) 评论(0) 分类:Python 前言 此处没有前言 粘包 在实现发送文件功能之前我们先来理解下粘包的问题,下面有两张图,我觉得很清晰的就可以理解到了. 正常情况下发送文件 第一步: 客户端把获取到的文件总大小(size=65426)先放到缓冲区,然后发送给服务端 第二步: 此时客户端接收到的文件总大小就是65426 粘包的问题下发送文件 第一步: 客户端把获取到的文件总大小(siz

使用Paramiko实现SSH登陆,文件上传下载

1,SSh登陆命令行实现: #!/usr/bin/env python # encoding: utf-8 import paramiko private_key_path = '/Users/aolens/.ssh/id_rsa' key = paramiko.RSAKey.from_private_key_file(private_key_path) ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.Aut

文件上传下载

1.文件上传 文件上传下载本质是通过Socket的字节流来传输数据的.所以,对于文件上传,我们可以从HttpRequest对象获取输入流,进而获取上传文件的内容.但是采用ServletAPI并不能获取获取对应文件的字节流,而是获取整个Socket的字节流,里面包括提交的参数.上传文件内容以及其他附加信息. Servlet API上传文件,代码如下 protected void doPost(HttpServletRequest request, HttpServletResponse respo

python模块paramiko的上传下载和远程执行命令

#!/usr/bin/python # -*- coding: utf-8 -*- import paramiko,os,datetime server_ip = '192.168.1.123' server_user = 'root' server_passwd = '10241010' server_port = 22 #local_dir='C:\Python27' #remote_dir='/soft2/nba/' def ssh_connect(): ssh = paramiko.SS

java web 文件上传下载

文件上传下载案例: 首先是此案例工程的目录结构: 处理上传: FileUploadServlet.java 1 package fnz.fileUploadTest; 2 3 import java.io.File; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.io.PrintWriter; 7 import java.text.SimpleDateFormat; 8 import java.

文件上传下载—servlet API实现

servlet API实现文件上传下载需要的jar包: UploadServlet.java package com.ymw.web.servlet; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.UUID; import javax.servl

Socket大文件上传

1 public sealed class SocketData 2 { 3 private SocketData() 4 { 5 } 6 7 public static SendFileMode SendFile(Socket socket, string fileName, int maxBufferLength) 8 { 9 SendFileMode flag = SendFileMode.Success; 10 try 11 { 12 using (Stream fs = new Fil