ooops, bring back r12

This commit is contained in:
nojhan 2010-09-08 20:58:30 +00:00
commit 927c189b92

View file

@ -60,7 +60,7 @@ class SSHTunnel(dict):
def __repr__(self): def __repr__(self):
# do not print all the informations by default # do not print all the informations by default
return "%i %i %s %s" % ( return "%i\t%i\t%s\t%s" % (
self['autossh_pid'], self['autossh_pid'],
self['local_port'], self['local_port'],
self['target_host'], self['target_host'],
@ -71,20 +71,22 @@ class SSHTunnel(dict):
class AutoSSHInstance(dict): class AutoSSHInstance(dict):
"""A dictionary that stores an autossh process""" """A dictionary that stores an autossh process"""
def __init__(self, pid = 0, local_port = 0, target_host = "Unknown",foreign_port = 0): def __init__(self, pid = 0, local_port = 0, via_host="Unknown", target_host = "Unknown",foreign_port = 0):
# some informations available on /proc # some informations available on /proc
self['pid'] = pid self['pid'] = pid
self['local_port'] = local_port self['local_port'] = local_port
self['via_host'] = via_host
self['target_host'] = target_host self['target_host'] = target_host
self['foreign_port'] = foreign_port self['foreign_port'] = foreign_port
self['tunnels'] = [] self['tunnels'] = []
def __repr__(self): def __repr__(self):
# single informations # single informations
repr = "%i %i %s %i" % ( repr = "%i\t%i\t%s\t%s\t%i" % (
self['pid'], self['pid'],
self['local_port'], self['local_port'],
self['via_host'],
self['target_host'], self['target_host'],
self['foreign_port']) self['foreign_port'])
@ -128,7 +130,13 @@ class AutoSSHTunnelMonitor(list):
def __repr__(self): def __repr__(self):
repr = "PID PORT HOST PORT TUNNELS\n" repr = "PID\tINPORT\tVIA\tHOST\tOUTPORT"
# only root can see tunnels connections
if os.geteuid() == 0:
repr += "\tTUNNELS"
repr += '\n'
# print each item in the list # print each item in the list
for t in self: for t in self:
@ -142,6 +150,8 @@ class AutoSSHTunnelMonitor(list):
# use the operator module # use the operator module
self[:] = sorted( self, key=itemgetter( key ) ) self[:] = sorted( self, key=itemgetter( key ) )
def get_autossh_instances(self):
"""Gather and parse autossh processes"""
def get_autossh_instances(self): def get_autossh_instances(self):
"""Gather and parse autossh processes""" """Gather and parse autossh processes"""
@ -173,7 +183,15 @@ class AutoSSHTunnelMonitor(list):
target_host = args[1] target_host = args[1]
foreign_port = int(args[2]) foreign_port = int(args[2])
auto = AutoSSHInstance( pid, local_port, target_host, foreign_port ) # find the hostname where the tunnel goes
via_host = "unknown"
for i in xrange( len(cmd)-1,0,-1 ):
if cmd[i][0] != '-':
via_host = cmd[i]
break
auto = AutoSSHInstance( pid, local_port, via_host, target_host, foreign_port )
autosshs += [auto] autosshs += [auto]
@ -248,6 +266,22 @@ class AutoSSHTunnelMonitor(list):
return tunnels return tunnels
def bind_tunnels(self, autosshs, tunnels):
"""Bind autossh process to the related ssh connections, according to the pid"""
for t in tunnels:
for i in autosshs:
if i['pid'] == t['autossh_pid']:
# add to the list of tunnels of the AutoSSHInstance instance
i['tunnels'] += [t]
return autosshs
# instanciation
tunnels += [ SSHTunnel( local_addr, local_port, foreign_addr, foreign_port, autohost, status, sshpid, ppid ) ]
return tunnels
def bind_tunnels(self, autosshs, tunnels): def bind_tunnels(self, autosshs, tunnels):
"""Bind autossh process to the related ssh connections, according to the pid""" """Bind autossh process to the related ssh connections, according to the pid"""
for t in tunnels: for t in tunnels:
@ -290,8 +324,8 @@ class monitorCurses:
self.ui_delay = 0.05 # seconds between two loops self.ui_delay = 0.05 # seconds between two loops
# colors # colors
self.colors_autossh = {'pid':0, 'local_port':3, 'target_host':2, 'foreign_port':3, 'tunnels_nb':4, 'tunnels_nb_none':1} self.colors_autossh = {'pid':0, 'local_port':3, 'via_host':2, 'target_host':2, 'foreign_port':3, 'tunnels_nb':4, 'tunnels_nb_none':1}
self.colors_highlight = {'pid':9, 'local_port':9, 'target_host':9, 'foreign_port':9, 'tunnels_nb':9, 'tunnels_nb_none':9} self.colors_highlight = {'pid':9, 'local_port':9, 'via_host':9, 'target_host':9, 'foreign_port':9, 'tunnels_nb':9, 'tunnels_nb_none':9}
self.colors_ssh = {'ssh_pid':0, 'status':4, 'status_out':1, 'local_address':2, 'local_port':3, 'foreign_address':2, 'foreign_port':3} self.colors_ssh = {'ssh_pid':0, 'status':4, 'status_out':1, 'local_address':2, 'local_port':3, 'foreign_address':2, 'foreign_port':3}
@ -307,7 +341,7 @@ class monitorCurses:
# first update counter # first update counter
last_update = time.clock() last_update = time.clock()
# infinit loop # infinite loop
while(1): while(1):
# wait some time # wait some time
@ -350,7 +384,8 @@ class monitorCurses:
os.kill( self.cur_pid, signal.SIGKILL ) os.kill( self.cur_pid, signal.SIGKILL )
# Switch to show ssh connections # Switch to show ssh connections
elif ch in 'tT': # only available for root
elif ch in 'tT' and os.getuid() == 0:
self.show_tunnels = not self.show_tunnels self.show_tunnels = not self.show_tunnels
# key down # key down
@ -382,7 +417,12 @@ class monitorCurses:
"""Generate the interface screen""" """Generate the interface screen"""
# First line: help # First line: help
self.scr.addstr(0,0, "[R]:reload autossh [K]:kill autossh [Q]:quit [T]:show tunnels connections\n", curses.color_pair(4) ) help_msg = "[R]:reload autossh [K]:kill autossh [Q]:quit"
if os.geteuid() == 0:
help_msg += " [T]:show tunnels connections"
help_msg += '\n'
self.scr.addstr(0,0, help_msg, curses.color_pair(4) )
self.scr.clrtoeol() self.scr.clrtoeol()
# Second line # Second line
@ -399,7 +439,10 @@ class monitorCurses:
self.cur_pid = -1 self.cur_pid = -1
# header line # header line
self.scr.addstr( "PID \tINPORT\tHOST \tOUTPORT\tCONNECTIONS", curses.color_pair(color) ) header_msg = "PID \tINPORT\tVIAHOST \tOUTHOST \tOUTPORT"
if os.geteuid() == 0:
header_msg += "\tCONNECTIONS"
self.scr.addstr( header_msg, curses.color_pair(color) )
self.scr.clrtoeol() self.scr.clrtoeol()
# for each autossh processes available in the monitor # for each autossh processes available in the monitor
@ -408,7 +451,7 @@ class monitorCurses:
self.add_autossh( l ) self.add_autossh( l )
# if one want to show connections # if one want to show connections
if self.show_tunnels: if self.show_tunnels and os.getuid() == 0:
self.add_tunnel( l ) self.add_tunnel( l )
self.scr.clrtobot() self.scr.clrtobot()
@ -451,6 +494,7 @@ class monitorCurses:
self.scr.addstr( '\n' ) self.scr.addstr( '\n' )
self.add_autossh_info('pid', line) self.add_autossh_info('pid', line)
self.add_autossh_info('local_port', line) self.add_autossh_info('local_port', line)
self.add_autossh_info('via_host', line)
self.add_autossh_info('target_host', line) self.add_autossh_info('target_host', line)
self.add_autossh_info('foreign_port', line) self.add_autossh_info('foreign_port', line)
@ -466,11 +510,14 @@ class monitorCurses:
self.scr.addstr( '|', curses.color_pair(self.colors_ssh['status_out']) ) self.scr.addstr( '|', curses.color_pair(self.colors_ssh['status_out']) )
else: else:
if os.geteuid() == 0:
# if there is no connection, display a "None" # if there is no connection, display a "None"
self.scr.addstr( 'None', curses.color_pair(self.colors_autossh['tunnels_nb_none']) ) self.scr.addstr( 'None', curses.color_pair(self.colors_autossh['tunnels_nb_none']) )
self.scr.clrtoeol() self.scr.clrtoeol()
def add_autossh_info( self, key, line ):
"""Add an information of an autossh process, in the configured color"""
def add_autossh_info( self, key, line ): def add_autossh_info( self, key, line ):
"""Add an information of an autossh process, in the configured color""" """Add an information of an autossh process, in the configured color"""
@ -482,7 +529,7 @@ class monitorCurses:
colors = self.colors_highlight colors = self.colors_highlight
txt = str(self.tm[line][key]) txt = str(self.tm[line][key])
if key == 'target_host': if key == 'target_host' or key == 'via_host':
# limit the size of the line to 20 # limit the size of the line to 20
# TODO avoid hard-coded constants # TODO avoid hard-coded constants
txt = str(self.tm[line][key]).ljust(20)[:20] txt = str(self.tm[line][key]).ljust(20)[:20]
@ -490,20 +537,20 @@ class monitorCurses:
self.scr.addstr( txt, curses.color_pair(colors[key]) ) self.scr.addstr( txt, curses.color_pair(colors[key]) )
self.scr.addstr( '\t', curses.color_pair(colors[key]) ) self.scr.addstr( '\t', curses.color_pair(colors[key]) )
if __name__ == "__main__": if __name__ == "__main__":
import sys import sys
from optparse import OptionParser from optparse import OptionParser
usage = """%prog [options] usage = """%prog [options]
A user interface to monitor existing SSH tunnel that are managed with autossh. A user interface to monitor existing SSH tunnel that are managed with autossh.
Called without options, ereshkigal displays a list of tunnels on the standard output.""" Called without options, ereshkigal displays a list of tunnels on the standard output.
Note: Users other than root will not see tunnels connections"""
parser = OptionParser(usage=usage) parser = OptionParser(usage=usage)
parser.add_option("-c", "--curses", action="store_true", dest="curses", default=False, parser.add_option("-c", "--curses", action="store_true", dest="curses", default=False,
help="start the user interface in text mode") help="start the user interface in text mode")
parser.add_option("-n", "--connections", action="store_true", dest="connections", default=False, parser.add_option("-n", "--connections", action="store_true", dest="connections", default=False,
help="display only SSH connections related to a tunnel") help="display only SSH connections related to a tunnel (only available as root)")
parser.add_option("-a", "--autossh", action="store_true", dest="autossh", default=False, parser.add_option("-a", "--autossh", action="store_true", dest="autossh", default=False,
help="display only the list of autossh processes") help="display only the list of autossh processes")
@ -561,9 +608,12 @@ Called without options, ereshkigal displays a list of tunnels on the standard ou
elif options.connections: elif options.connections:
tm = AutoSSHTunnelMonitor() tm = AutoSSHTunnelMonitor()
# do not call update() but only get connections # do not call update() but only get connections
if os.geteuid() == 0:
con = tm.get_connections() con = tm.get_connections()
for c in con: for c in con:
print con print con
else:
print "Error: only root can see SSH tunnels connections"
elif options.autossh: elif options.autossh: