Skip to content

Instantly share code, notes, and snippets.

@mogeko
Last active February 12, 2020 14:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mogeko/7bf5a21700868a9c7b1243baa165e8d0 to your computer and use it in GitHub Desktop.
Save mogeko/7bf5a21700868a9c7b1243baa165e8d0 to your computer and use it in GitHub Desktop.
一个简单的本地 HTTP 服务器,用于在局域网中分享文件。python3 -m http.server 的升级版
#!/bin/sh
/sbin/ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{print $2}'|tr -d 'addr:' | while read ip; do python3 -m http.server 8000 --bind $ip; done
@mogeko
Copy link
Author

mogeko commented Oct 30, 2018

众所周知,在 shell 中执行python3 -m http.server可以很轻松的创建一个 HTTP 服务器来分享文件。
但是默认情况下 python会以http://0.0.0.0:8000为地址创建服务器。此时,局域网中用户是不能直接访问http://0.0.0.0:8000的,而应该访问http://[分享者的 IP]:8000。但是用户往往不清楚分享者的 (局域网) IP 地址是多少

2018-10-30 18-51-45

于是我改进了这一命令,改为:

/sbin/ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{print $2}'|tr -d 'addr:' | while read ip; do python3 -m http.server 8000 --bind $ip; done

改进后,会自动以http://[分享者的 IP]:8000为地址创建服务器,并显示到屏幕上

2018-10-30 19-06-52

依赖

  • python3
  • net-tools (ifconfig)

使用

在终端中执行:

/sbin/ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{print $2}'|tr -d 'addr:' | while read ip; do python3 -m http.server 8000 --bind $ip; done

应该没人想记这么长的命令吧?我们可以使用脚本来帮助我们

我原本准备用 alias 将此命令设置成别名,但似乎用不了

不过我们可以曲线救国,首先创建一个脚本文件 : HTTPServer(或者下载上面那个文件),赋予可执行的权限,然后将脚本文件放到/usr/local/bin/目录下。

在任意位置执行HTTPServer即可使用

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment