1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
|
#!/usr/bin/env python
"""Back door shell server
This exposes a shell terminal emulator on a socket.
--hostname : sets the remote host name to open an ssh connection to.
--username : sets the user name to login with
--password : (optional) sets the password to login with
--port : set the local port for the server to listen on
"""
# Having the password on the command line is not a good idea, but
# then this entire project is probably not the most security concious thing
# I've ever built. This should be considered an experimental tool.
import pxssh, pexpect, ANSI
import socket
import time, sys, os, getopt, getpass
import threading
def exit_with_usage(exit_code=1):
print globals()['__doc__']
os._exit(exit_code)
class roller (threading.Thread):
"""This runs a function in a loop in a thread."""
def __init__(self, interval, function, args=[], kwargs={}):
"""The interval parameter defines time between each call to the function.
"""
threading.Thread.__init__(self)
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.finished = threading.Event()
def cancel(self):
"""Stop the roller."""
self.finished.set()
def run(self):
while not self.finished.isSet():
# self.finished.wait(self.interval)
self.function(*self.args, **self.kwargs)
def daemonize (stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
'''This forks the current process into a daemon.
Almost none of this is necessary (or advisable) if your daemon
is being started by inetd. In that case, stdin, stdout and stderr are
all set up for you to refer to the network connection, and the fork()s
and session manipulation should not be done (to avoid confusing inetd).
Only the chdir() and umask() steps remain as useful.
References:
UNIX Programming FAQ
1.7 How do I get my program to act like a daemon?
http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
Advanced Programming in the Unix Environment
W. Richard Stevens, 1992, Addison-Wesley, ISBN 0-201-56317-7.
The stdin, stdout, and stderr arguments are file names that
will be opened and be used to replace the standard file descriptors
in sys.stdin, sys.stdout, and sys.stderr.
These arguments are optional and default to /dev/null.
Note that stderr is opened unbuffered, so
if it shares a file with stdout then interleaved output
may not appear in the order that you expect.
'''
# Do first fork.
try:
pid = os.fork()
if pid > 0:
sys.exit(0) # Exit first parent.
except OSError, e:
sys.stderr.write ("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror) )
sys.exit(1)
# Decouple from parent environment.
os.chdir("/")
os.umask(0)
os.setsid()
# Do second fork.
try:
pid = os.fork()
if pid > 0:
sys.exit(0) # Exit second parent.
except OSError, e:
sys.stderr.write ("fork #2 failed: (%d) %s\n" % (e.errno, e.strerror) )
sys.exit(1)
# Now I am a daemon!
# Redirect standard file descriptors.
si = open(stdin, 'r')
so = open(stdout, 'a+')
se = open(stderr, 'a+', 0)
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
# I now return as the daemon
return 0
def add_cursor_blink (response, row, col):
i = (row-1) * 80 + col
return response[:i]+'<img src="http://www.noah.org/cursor.gif">'+response[i:]
def endless_poll (child, prompt, screen, refresh_timeout=1):
"""This keeps the screen updated with the output of the child.
This runs in a separate thread.
"""
child.logfile = screen
while True:
child.prompt (timeout=refresh_timeout)
#i = child.expect ([prompt, pexpect.TIMEOUT], timeout=refresh_timeout)
def main ():
try:
optlist, args = getopt.getopt(sys.argv[1:], 'h?d', ['help','h','?', 'hostname', 'username', 'password', 'port'])
except Exception, e:
print str(e)
exit_with_usage()
command_line_options = dict(optlist)
options = dict(optlist)
# There are a million ways to cry for help. These are but a few of them.
if [elem for elem in command_line_options if elem in ['-h','--h','-?','--?','--help']]:
exit_with_usage(0)
hostname = "127.0.0.1"
port = 1664
username = os.getenv('USER')
password = ""
if '-d' in options:
daemon_mode = True
else:
daemon_mode = False
if '--hostname' in options:
hostname = options['--hostname']
if '--port' in options:
port = int(options['--port'])
if '--username' in options:
username = options['--username']
print "Login for %s@%s:%s" % (username, hostname, port)
if '--password' in options:
password = options['--password']
else:
password = getpass.getpass('password: ')
#if daemon_mode:
# print "daemonizing server"
# daemonize ()
#daemonize('/dev/null','/tmp/daemon.log','/tmp/daemon.log')
sys.stdout.write ('server started with pid %d\n' % os.getpid() )
virtual_screen = ANSI.ANSI (24,80)
child = pxssh.pxssh()
child.login (hostname, username, password)
print 'created shell. command line prompt is', child.PROMPT
#child.sendline ('stty -echo')
virtual_screen.write (child.before)
virtual_screen.write (child.after)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
localhost = '127.0.0.1'
s.bind((localhost, port))
print 'Listen'
s.listen(1)
print 'Accept'
r = roller (0.01, endless_poll, (child, child.PROMPT, virtual_screen))
r.start()
print "screen poll updater started in background thread"
sys.stdout.flush()
try:
while True:
conn, addr = s.accept()
print 'Connected by', addr
data = conn.recv(1024)
request = data.split(' ', 1)
if len(request) < 2:
conn.send(error_response('request did not have enough arguments.'))
conn.close()
continue
cmd = request[0].strip()
arg = request[1].strip()
if cmd == 'command' or cmd == 'pretty':
child.sendline (arg)
child.prompt(timeout=1)
elif cmd == 'refresh':
pass
shell_window = pretty_box(virtual_screen.rows,virtual_screen.cols,str(virtual_screen))
elif cmd == 'skip':
# Wait until the TIMEOUT then throw away all data from the child.
# Use to catch up the screen with the shell if state gets out of sync.
child.expect (pexpect.TIMEOUT)
sh_response = child.before.replace ('\r', '')
virtual_screen.write (sh_response)
if cmd == 'command':
shell_window = virtual_screen.dump()
elif cmd == 'pretty':
shell_window = pretty_box(virtual_screen.rows,virtual_screen.cols,str(virtual_screen))
response = []
response.append ('%03d' % virtual_screen.rows)
response.append ('%03d' % virtual_screen.cols)
response.append (shell_window)
#response = add_cursor_blink (response, row, col)
sent = conn.send('\n'.join(response))
if sent < len (response):
print "Sent is too short. Some data was cut off."
conn.close()
if arg == 'exit':
s.close()
break
finally:
print "cleaning up socket"
s.close()
def pretty_box (rows, cols, s):
"""This puts an ASCII text box around the given string, s.
"""
top_bot = '+' + '-'*cols + '+\n'
return top_bot + '\n'.join(['|'+line+'|' for line in s.split('\n')]) + '\n' + top_bot
def error_response (msg):
response = []
response.append ('000')
response.append ('000')
response.append ("""{REQUEST} {ARGUMENT}
{REQUEST} may be one of the following:
command : Run the ARGUMENT as a shell command. Returns raw screen array.
pretty : Like 'command', but formats the screen array for printing.
skip : Use to catch up the screen with the shell if state gets out of sync.
Example:
pretty ls -l
""")
response.append (msg)
return '\n'.join(response)
if __name__ == "__main__":
# daemonize('/dev/null','/tmp/daemon.log','/tmp/daemon.log')
main()
|