是否可以使用python将文本文件从服务器传输到客户端?

时间:2015-06-01 09:13:00

标签: python sockets client-server

我是python的新手,并在python中为server-client编写了代码。代码将文件o / p从服务器发送到客户端控制台。 我的代码:

from thread import *
import threading
import time
import psutil
import itertools
import ctypes
import string
import os
import sys
import socket

exitFlag = 0

#function returning the list of all the valid partitions of the system...
def drives():
    drive_bitmask = ctypes.cdll.kernel32.GetLogicalDrives()
    return list(itertools.compress(string.ascii_uppercase,map(lambda x:ord(x) - ord('0'), bin(drive_bitmask)[:1:-1])))



def proc_info(conn,addr): # prints the process's info which match the keyword....... SERVER SIDE
    f0=open('abc.txt','a+')
    conn.send('Welcome to the server\n')
    name=[]
    c=drives()
    k=0
    conn.send("Enter the key...\n") # for authentication purposes...e.g.here the key is 1
    t=conn.recv(8)
    if(t!='1'):  #WRONG KEY....INVALID USER
        conn.send("\nInvalid key..teminating the connection.....ABORT\n")
        conn.close()

    else:
        r=""
        conn.send("\nEnter the process keyword ..Press # @ the end ") # e.g. 'Sk' for Skype
        d=conn.recv(65536).decode('utf-8')
        while(d!='#'):
            r=r+str(d)
            d=conn.recv(65536).decode('utf-8') ## PROBLEMATIC STATEMENT
        f0.write(d)
        for p in psutil.pids(): # iterates through all the pids of the processes obtained
            try:
                p1=psutil.Process(p)
                if(r in p1.name()):

                    p2=p1.get_memory_info()
                    t=p1.name()+' '
                    d=str(p)+' '

                    f0.write(d)
                    f0.write(t)
                    conn.send(d)# prints the pid of the process
                    conn.send(t),# prints the name of the process
                    d=str(p2[0]/(1024*1024))+' '
                    conn.send(d) # print memory in MB
                    f0.write(d)
                    f0.write('MB\n')
                    conn.send('MB\n')
                    for connect in p1.connections(kind='tcp'):
                        d=str(connect.laddr[0])+' '
                        f0.write(d)
                        conn.send(d) # prints ip
                        d=str(connect.laddr[1])+' '
                        f0.write(d)
                        conn.send(d) # prints tcp ports
                        f0.write('\n')
                        conn.send('\n')
                    if((p2[0]/(1024*1024))>=100):
                        m=p1.name()

                    for l in c:
                        f=0
                        for root, dirs, files in os.walk(l): # walks through the entire file system of the Windows OS
                            #f=0
                            for name in files:
                                if name==m:
                                    #p1.kill()
                                    f=1
                                    #os.system(os.path.abspath(os.path.join(root, name)))
                                    #subprocess.Popen(os.path.abspath(os.path.join(root,name))) # relaunches the killed process
                                    #if(p):
                                    break
                            if(f==1):
                                break

                        if(f==1):
                            break

                    #l=l+1

            except psutil.AccessDenied:
                pass

            except psutil.NoSuchProcess:
                pass
            else:
                continue
        f0.close()
        conn.close()


class serverThread(threading.Thread): # Thread class for Server(FOR LISTENING)
    def __init__(self, threadID, name,):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name

    def run(self):   
        threadLock.acquire()
        host=raw_input("Enter the hostname.....")
        HOST=socket.gethostbyname(host)   
        PORT=60000 # specific port available
        s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        print 'Socket created' 
        #Bind socket to local host and port
        try:
            s.bind((HOST, PORT))
        except socket.error as msg:
            print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
            sys.exit()
        print 'Socket bind complete'
        s.listen(10) # no of connections @ one time
        print self.name+' now listening'
        threadLock.release()

        while 1:
            conn, addr = s.accept() # connection gets established here..
            print 'Connected with ' + addr[0] + ':' + str(addr[1])
            conn.send('Thank you for connecting')
            # creates a new thread for the client services and processes the parameter and sends it back to the client
            start_new_thread(proc_info,(conn,addr))

        s.close()


threadLock=threading.Lock()

thread1 =serverThread(1,"Server 1")
thread1.start() # starting the server thread...

此代码目前将输出打印到客户端控制台。是否可以将整个文本文件发送到客户端? 例如,如果我有" xyz.txt"在我的服务器上,可以复制" xyz.txt"的文本文件。在客户端创建?

1 个答案:

答案 0 :(得分:0)

如果您只想将文件传输到客户端,则无需再构建另一个轮子,只需使用:

python -m SimpleHTTPServer 8081

这将构建一个简单的文件服务器,客户端可以选择使用浏览器下载文件,也可以选择wget

如果您无法控制客户端(即他们不会运行您编写的代码),则很难将文件保存在磁盘上。