#!/usr/bin/python
"""
Serial to Telnet Proxy
Creates a proxy between a TCP socket and a serial console.
Copyright (C) 2009 Justin Lee
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
"""
import sys, os, socket, signal, string
# defaults
_debug = 0
bind = '127.0.0.1'
port = '2300'
print "Serial to Telnet Proxy Copyright (C) 2009 Justin Lee"
print "This program comes with ABSOLUTELY NO WARRANTY. This is free software, and you"
print "are welcome to redistribute it under certain conditions. For details, see the"
print "full license at http://www.gnu.org/licenses/gpl-3.0.html"
print ""
def usage():
print "Usage:", sys.argv[0], "", "[port]"
print "E.g. :", sys.argv[0], "/dev/cu.PL2303-0000101D"
print "E.g. :", sys.argv[0], "/dev/cu.PL2303-0000101D", "2300"
def info(s):
print s
return
def debug(s):
if _debug: print "[DEBUG]", s
return
def proxy(fd, cs):
# send IAC WILL ECHO
cs.send("\xFF\xFB\x01")
# send IAC WILL SUPPRESS_GO_AHEAD
cs.send("\xFF\xFB\x03")
# send IAC WON'T LINEMODE
cs.send("\xFF\xFC\x22")
# fork process
debug("Forking process")
pid = os.fork()
# child - serial to net
if pid == 0:
while 1:
s = os.read(fd, 4096)
if not s: break
for c in s:
# ignore telnet control characters
# ignore NULL (fixes cisco bug)
if ord(c) < 240 and ord(c) > 0:
cs.sendall(c)
# parent - net to serial
else:
while 1:
s = cs.recv(4096)
if not s: break
for c in s:
# ignore telnet control characters
# ignore NULL (fixes cisco bug)
if ord(c) < 240 and ord(c) > 0:
os.write(fd, c)
os.kill(pid, signal.SIGKILL)
os.wait()
cs.close()
# show usage if there's insufficient args
if len(sys.argv) < 2:
usage()
exit(1)
# get input from command line
dev = sys.argv[1]
if len(sys.argv) == 3: port = sys.argv[2]
# open device for read/write
fd = os.open(dev, os.O_RDWR)
debug("Device " + dev + " opened for read/write.")
# create socket to listen
ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ss.bind((bind, int(port)))
ss.listen(1)
info("Listening on " + bind + ":" + port + ".")
# loop and accept incoming connections
while 1:
debug("Waiting for socket connection")
cs, ca = ss.accept()
info("Accepted connection from " + ca[0] + ":" + str(ca[1]) + ".")
# start proxy
proxy(fd, cs)
info("Connection from " + ca[0] + ":" + str(ca[1]) + " closed.")
ss.close()
os.close(fd)