Python TCP 服务器上文件是否存在

0 投票
2 回答
662 浏览
提问于 2025-04-17 19:42

我正在尝试用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()

我不知道怎么运行一个命令(RUNCOMMAND),来检查客户端上是否存在某个文件。还有,是否有办法检查客户端使用的是什么操作系统,以便运行不同的命令(比如,Linux的文件查找命令和Windows的会不一样)。我完全理解如果这不可能,但我真的希望能找到办法来实现这个。

非常感谢!

2 个回答

1

XMLRPC可能对你有帮助。
XML-RPC是一种远程过程调用的方法,它通过HTTP传输XML数据。
你可以查看这个链接了解更多信息:http://docs.python.org/2/library/xmlrpclib.html

0

你可以看看一个很实用的叫做 bottle.py 的小型服务器。它非常适合处理一些小型的服务器任务,而且它还支持 Http 协议。你只需要把你的代码放在一个文件里就可以了。更多信息可以查看这个链接:http://bottlepy.org

下面的代码可以在 http://blah:8090/get/file 或者 http://blah:8090/exists/file 这个地址上运行,所以如果你想查看 /etc/hosts 文件的内容,可以访问 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)

在运行方法中有一个叫做 reloader 的选项,它允许你在不手动重启服务器的情况下编辑代码。这非常方便。

撰写回答