python接受路由器curl命令put过来的文件

路由器需要备份一些分区文件和radiao校正信息,但是厂家固件的ssh server不支持sftp协议
需要用curl命令将 相关文件上传到 电脑

python3 -m http.server --directory /dev/shm

python自带的http server模块,可以让 路由器很方便地从 电脑中获取文件
但是上传就不行了
Receiving files over HTTP with Python
这篇文章介绍了一段代码,可以很方便地实现我想要的功能

#!/usr/bin/env python

"""Extend Python's built in HTTP server to save files

curl or wget can be used to send files with options similar to the following

  curl -X PUT --upload-file somefile.txt http://localhost:8000
  wget -O- --method=PUT --body-file=somefile.txt http://localhost:8000/somefile.txt

__Note__: curl automatically appends the filename onto the end of the URL so
the path can be omitted.

"""
import os
try:
    import http.server as server
except ImportError:
    # Handle Python 2.x
    import SimpleHTTPServer as server

class HTTPRequestHandler(server.SimpleHTTPRequestHandler):
    """Extend SimpleHTTPRequestHandler to handle PUT requests"""
    def do_PUT(self):
        """Save a file following a HTTP PUT request"""
        filename = os.path.basename(self.path)

        # Don't overwrite files
        if os.path.exists(filename):
            self.send_response(409, 'Conflict')
            self.end_headers()
            reply_body = '"%s" already exists\n' % filename
            self.wfile.write(reply_body.encode('utf-8'))
            return

        file_length = int(self.headers['Content-Length'])
        with open(filename, 'wb') as output_file:
            output_file.write(self.rfile.read(file_length))
        self.send_response(201, 'Created')
        self.end_headers()
        reply_body = 'Saved "%s"\n' % filename
        self.wfile.write(reply_body.encode('utf-8'))

if __name__ == '__main__':
    server.test(HandlerClass=HTTPRequestHandler)

保存为 http_put_server.py

python3 http_put_server.py

在路由器上运行

 curl -X PUT --upload-file mtd0  http://192.168.168.167:8000

另外一些改进版本
https://gist.github.com/darkr4y/761d7536100d2124f5d0db36d4890109
https://gist.github.com/touilleMan/eb02ea40b93e52604938

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注