如果你需要在局域网分享文件,可以使用QQ微信等办公软件挺方便的,但是如果是大文件,比如说好几G的,先不说速度慢,由于限制,还不一定能发给别人
但如果你的电脑上安装了python(没有的话也可以自己安装一个,占用资源很小),我们可以使用它自带的http模块运行一个http服务,这样局域网内的设备都能通过浏览器去访问和下载文件了
由于走的是局域网路线,所以传输速度基本上取决于你的路由器或交换机的速度
1.命令行模式
打开cmd或者powershell,使用python命令启动http.server模块
python -m http.server 端口 # 端口可以不写,默认是8000
它提示成功之后我们就可以在浏览器根据你的ip端口进行访问了,此处ip是局域网ip,可以通过在cmd输入ipconfig查看你本机局域网ip
2.封装代码
上面的步骤是先进入你要分享的文件夹然后再运行http服务,而且还需要手动查看本机ip,我们完全可以写一个代码,把这些步骤全部整合在一起,把py文件的默认打开方式改为python,即把封装好的脚本复制到你要分享的文件夹,然后双击运行即可
import contextlib
import os
import socket
import sys
import argparse
import traceback
from functools import partial
from http.server import BaseHTTPRequestHandler, CGIHTTPRequestHandler, SimpleHTTPRequestHandler, ThreadingHTTPServer
def _get_best_family(*address):
infos = socket.getaddrinfo(
*address,
type=socket.SOCK_STREAM,
flags=socket.AI_PASSIVE,
)
family, type, proto, canonname, sockaddr = next(iter(infos))
return family, sockaddr
def test(HandlerClass=BaseHTTPRequestHandler,
ServerClass=ThreadingHTTPServer,
protocol="HTTP/1.0", port=8000, bind=None):
"""Test the HTTP request handler class.
This runs an HTTP server on port 8000 (or the port argument).
"""
ServerClass.address_family, addr = _get_best_family(bind, port)
HandlerClass.protocol_version = protocol
with ServerClass(addr, HandlerClass) as httpd:
host, port = httpd.socket.getsockname()[:2]
url_host = f'[{host}]' if ':' in host else host
print(
f"Serving HTTP on {host} port {port} "
f"(http://{url_host}:{port}/) ..."
)
try:
httpd.serve_forever()
except KeyboardInterrupt:
print("\nKeyboard interrupt received, exiting.")
sys.exit(0)
def runserver(port=8000):
parser = argparse.ArgumentParser()
parser.add_argument('--cgi', action='store_true',
help='Run as CGI Server')
parser.add_argument('--bind', '-b', metavar='ADDRESS',
help='Specify alternate bind address '
'[default: all interfaces]')
parser.add_argument('--directory', '-d', default=os.getcwd(),
help='Specify alternative directory '
'[default:current directory]')
parser.add_argument('port', action='store',
default=port, type=int,
nargs='?',
help='Specify alternate port [default: 8000]')
args = parser.parse_args()
if args.cgi:
handler_class = CGIHTTPRequestHandler
else:
handler_class = partial(SimpleHTTPRequestHandler, directory=args.directory)
# ensure dual-stack is not disabled; ref #38907
class DualStackServer(ThreadingHTTPServer):
def server_bind(self):
# suppress exception when protocol is IPv4
with contextlib.suppress(Exception):
self.socket.setsockopt(
socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
return super().server_bind()
test(
HandlerClass=handler_class,
ServerClass=DualStackServer,
port=args.port,
bind=args.bind,
)
def get_host_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(('8.8.8.8', 80))
ip = s.getsockname()[0]
finally:
s.close()
return ip
if __name__ == '__main__':
print("""
使用说明:
1.请确保该路径以及子路径没有 --敏感文件--
2.仅限局域网访问(比如大家都连接同一个路由器)
3.共享路径是运行该程序的文件夹,局域网内所有人都能访问和下载文件
""")
print("共享路径: {}".format(os.getcwd()))
port = 80 # 默认端口是8000,在浏览器默认访问80端口
try:
ip = get_host_ip()
print("启动程序成功")
print("请在浏览器访问URL:{}".format(ip))
runserver(port)
except Exception as e:
print("启动程序失败:{}".format(traceback.format_exc()))