telnet and http server on NodeMCU v2

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

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)`.

Thanks a lot! I precisely needed a way to telnet in while having the http server for normal operations.

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.