Submitted by cjj on
The NodeMCU v2 firmware for esp8266 only allows one TCP server. Usually, one will use this to serve a status page for the wireless unit. But, sometimes, maybe during development, it is desirable to also have a telnet access to the unit over WIFI to do some tweaking. Here, we achieve this by leaving a backdoor on the http port. By connecting to port 80 with telnet and enter "telnet" as the first input line, the connection is switch to a telnet service allows direct interaction with the Lua interpreter. The actual code is listed below:
srv=net.createServer(net.TCP,180) srv:listen(80,function(c) c:on("receive",function(c,d) if d:sub(1,6) == "telnet" then -- switch to telnet service node.output(function(s) if c ~= nil then c:send(s) end end,0) c:on("receive",function(c,d) if d:byte(1) == 4 then c:close() -- ctrl-d to exit else node.input(d) end end) c:on("disconnection",function(c) node.output(nil) end) print("Welcome to NodeMCU") node.input("\r\n") return end if d:sub(1,5) ~= "GET /" then -- only process GET method c:close() return end -- serve a webpage c:send("<!DOCTYPE html>\n<html>\n<head>\n") c:send("<title>Hello World!</title>\n") c:send("</head>\n<body>\n") c:send("<h1>Hello World!</h1>\n") c:send("</body>\n</html>\n") c:close() end) end)
Comments
Anonymous replied on Permalink
The code contains a typo that
The code contains a typo that will make it crash when you try to access the website:
Instead of `data:sub(1,5)`, it should be `d:sub(1,5)`.
cjj replied on Permalink
Thanks for the catch!
It has been corrected.
Alex replied on Permalink
Great
Thanks a lot! I precisely needed a way to telnet in while having the http server for normal operations.