簡體   English   中英

是否可以使用python將文本文件從服務器傳輸到客戶端?

[英]Is it possible to transfer a text file from server to client using python?

我是python的新手,並用python編寫了服務器-客戶端代碼。 該代碼將文件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”的副本文本文件?

如果您只想將文件傳輸到客戶端,則無需構建另一個輪子,只需使用以下命令:

python -m SimpleHTTPServer 8081

這將構建一個簡單的文件服務器,客戶端可以選擇使用瀏覽器或僅使用wget下載文件。

而且,如果您無法控制客戶端(也就是說,他們將無法運行您編寫的代碼),則很難在其磁盤上保存文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM