2013-03-20 47 views
0

我想在python中創建一個TCP端口服務器。這是我到目前爲止的代碼:客戶端上是否存在文件Python TCP服務器

import socket 

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
sock.bind(('',4000)) 
sock.listen(1) 

while 1: 
    client, address = sock.accept() 
    fileexists = client.RUNCOMMAND(does the file exist?) 

    if fileexists = 0: 
      client.close() 
    else if: 
     filedata = client.RUNCOMMAND(get the contents of the file) 

     if filedata = "abcdefgh": 
       client.send('Transfer file accepted.') 
     else: 
       client.send('Whoops, seems like you have a corrupted file!') 

    client.close() 

我只是不知道如何運行一個命令(RUNCOMMMAND)如果一個文件在客戶端上存在將檢查。 另外,有沒有辦法檢查客戶機上運行不同命令的操作系統(例如,Linux將使用不同於windows的文件查找器命令)。我完全明白這是不可能的,但我真的希望有辦法做到這一點。

非常感謝。

+0

這看起來像一個服務器的代碼,除非你正在做一個P2P的事情。在客戶端上運行哪些代碼並連接到服務器?只有該機器可以知道文件是否存在,所以服務器將不得不發送文件請求,並且「文件存在?」將在運行自己的客戶端代碼的客戶端機器上進行檢查。 – Paul 2013-03-20 03:40:52

+0

@Paul客戶端代碼是連接到端口4000併發送數據的基本python。我想在這裏的行動是有一個ssh樣的文件檢查系統。如果我在客戶端執行了操作,並顯示響應「是,我擁有該文件」,則任何人都可以連接到服務器並鍵入「是的,我有文件」以進入。這實際上是訪問密碼服務器。這是一個問題,我希望服務器檢查文件是否存在完全封鎖蠻力嘗試。如果該文件不存在,服務器將拒絕而不允許輸入密碼。 – 2013-03-20 04:47:25

回答

0

你可能想看看非常方便bottle.py微型服務器。它非常適合這樣的小型服務器任務,並且您可以在此之上獲得Http協議。您只需在代碼中包含一個文件。 http://bottlepy.org

這裏是代碼將從http://blah:8090/get/filehttp://blah:8090/exists/file這樣的工作,看看在/ etc內容/主機將是http://blah:8090/get/etc/hosts

#!/usr/bin/python 
import bottle 
import os.path 


@bottle.route("/get/<filepath:path>") 
def index(filepath): 
    filepath = "/" + filepath 
    print "getting", filepath 
    if not os.path.exists(filepath): 
     return "file not found" 

    print open(filepath).read() # prints file 
    return '<br>'.join(open(filepath).read().split("\n")) # prints file with <br> for browser readability 

@bottle.route("/exists/<filepath:path>") 
def test(filepath): 
    filepath = "/" + filepath 
    return str(os.path.exists(filepath)) 


bottle.run(host='0.0.0.0', port=8090, reloader=True) 

的run方法reloader選項,讓您無需手動編輯代碼重新啓動服務器。它非常方便。