2013-03-20 49 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选项,让您无需手动编辑代码重新启动服务器。它非常方便。