indentation fix + execution permission

This commit is contained in:
nojhan 2010-01-31 22:02:58 +00:00
commit 920aebb82e

View file

@ -4,18 +4,18 @@
# Ereshkigal is an AutoSSH tunnel monitor # Ereshkigal is an AutoSSH tunnel monitor
# It gives a curses user interface to monitor existing SSH tunnel that are managed with autossh. # It gives a curses user interface to monitor existing SSH tunnel that are managed with autossh.
# #
# This program is free software: you can redistribute it and/or modify # 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 # it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
# Author : Johann "nojhan" Dréo <nojhan@gmail.com> # Author : Johann "nojhan" Dréo <nojhan@gmail.com>
# #
@ -31,232 +31,232 @@ import subprocess
from operator import itemgetter from operator import itemgetter
class SSHTunnel(dict): class SSHTunnel(dict):
"""A dictionary that stores an SSH connection related to a tunnel""" """A dictionary that stores an SSH connection related to a tunnel"""
def __init__(self, def __init__(self,
local_address = '1.1.1.1', local_address = '1.1.1.1',
local_port = 0, local_port = 0,
foreign_address = '1.1.1.1', foreign_address = '1.1.1.1',
foreign_port = 0, foreign_port = 0,
target_host = "Unknown", target_host = "Unknown",
status = 'UNKNOWN', status = 'UNKNOWN',
ssh_pid = 0, ssh_pid = 0,
autossh_pid = 0 autossh_pid = 0
): ):
# informations available with netstat # informations available with netstat
self['local_address'] = local_address self['local_address'] = local_address
self['local_port'] = local_port self['local_port'] = local_port
self['foreign_address'] = foreign_address self['foreign_address'] = foreign_address
self['foreign_port'] = foreign_port self['foreign_port'] = foreign_port
self['target_host'] = target_host self['target_host'] = target_host
self['status'] = status self['status'] = status
self['ssh_pid'] = ssh_pid self['ssh_pid'] = ssh_pid
self['autossh_pid'] = autossh_pid self['autossh_pid'] = autossh_pid
# would be nice to have an estimation of the connections latency # would be nice to have an estimation of the connections latency
#self.latency = 0 #self.latency = 0
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 %i %s %s" % (
self['autossh_pid'], self['autossh_pid'],
self['local_port'], self['local_port'],
self['target_host'], self['target_host'],
self['status'] self['status']
) )
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, 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['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 %i %s %i" % (
self['pid'], self['pid'],
self['local_port'], self['local_port'],
self['target_host'], self['target_host'],
self['foreign_port']) self['foreign_port'])
# list of tunnels linked to this process # list of tunnels linked to this process
for t in self['tunnels']: for t in self['tunnels']:
repr += "\n\t%s" % t repr += "\n\t%s" % t
return repr return repr
class AutoSSHTunnelMonitor(list): class AutoSSHTunnelMonitor(list):
"""List of existing autossh processes and ssh connections""" """List of existing autossh processes and ssh connections"""
def __init__(self): def __init__(self):
"""Warning: the initialization does not gather tunnels informations, use update() to do so""" """Warning: the initialization does not gather tunnels informations, use update() to do so"""
# command that display network connections # command that display network connections
self.network_cmd = "netstat -ntp" self.network_cmd = "netstat -ntp"
# command that display processes # command that display processes
self.ps_cmd = "ps ax" self.ps_cmd = "ps ax"
# do not perform update by default # do not perform update by default
# this is necessary because one may want # this is necessary because one may want
# only a list of connections OR autossh processes # only a list of connections OR autossh processes
#self.update() #self.update()
def update(self): def update(self):
"""Gather and parse informations from the operating system""" """Gather and parse informations from the operating system"""
# autossh processes # autossh processes
autosshs = self.get_autossh_instances() autosshs = self.get_autossh_instances()
# ssh connections related to a tunnel # ssh connections related to a tunnel
connections = self.get_connections() connections = self.get_connections()
# bind existing connections to autossh processes # bind existing connections to autossh processes
self[:] = self.bind_tunnels(autosshs, connections) self[:] = self.bind_tunnels(autosshs, connections)
# sort on a given key # sort on a given key
self.sort_on( 'local_port') self.sort_on( 'local_port')
def __repr__(self): def __repr__(self):
repr = "PID PORT HOST PORT TUNNELS\n" repr = "PID PORT HOST PORT TUNNELS\n"
# print each item in the list
for t in self:
repr += "%s\n" % t
return repr
# print each item in the list
for t in self:
repr += "%s\n" % t
return repr def sort_on(self, key = 'autossh_pid' ):
"""Sort items on a given key"""
# use the operator module
def sort_on(self, key = 'autossh_pid' ): self[:] = sorted( self, key=itemgetter( key ) )
"""Sort items on a given key"""
# use the operator module
self[:] = sorted( self, key=itemgetter( key ) )
def get_autossh_instances(self): def get_autossh_instances(self):
"""Gather and parse autossh processes""" """Gather and parse autossh processes"""
# call the command # call the command
#status = os.popen3( self.ps_cmd ) #status = os.popen3( self.ps_cmd )
p = subprocess.Popen( self.ps_cmd, shell=True, p = subprocess.Popen( self.ps_cmd, shell=True,
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
status = (p.stdin, p.stdout, p.stderr) status = (p.stdin, p.stdout, p.stderr)
# list of processes with the "autossh" string # list of processes with the "autossh" string
status_list = [ps for ps in status[1].readlines() if "autossh" in ps] status_list = [ps for ps in status[1].readlines() if "autossh" in ps]
# split the process line if it contains a "-L" # split the process line if it contains a "-L"
list = [i.split() for i in status_list if '-L' in i] list = [i.split() for i in status_list if '-L' in i]
autosshs = [] autosshs = []
for cmd in list: for cmd in list:
# split the command in order to obtain arguments to the -L option # split the command in order to obtain arguments to the -L option
args = [i.strip('-').strip('-').strip('L') for i in cmd if '-L' in i][0].split(':') args = [i.strip('-').strip('-').strip('L') for i in cmd if '-L' in i][0].split(':')
pid = int(cmd[0]) pid = int(cmd[0])
local_port = int(args[0]) local_port = int(args[0])
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 ) auto = AutoSSHInstance( pid, local_port, target_host, foreign_port )
autosshs += [auto] autosshs += [auto]
return autosshs return autosshs
def get_connections(self): def get_connections(self):
"""Gather and parse ssh connections related to a tunnel""" """Gather and parse ssh connections related to a tunnel"""
#status = os.popen3( self.network_cmd ) #status = os.popen3( self.network_cmd )
p = subprocess.Popen( self.network_cmd, shell=True, p = subprocess.Popen( self.network_cmd, shell=True,
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
status = (p.stdin, p.stdout, p.stderr) status = (p.stdin, p.stdout, p.stderr)
status_list = status[1].readlines() status_list = status[1].readlines()
list = [i.split() for i in status_list if 'ssh' in i] list = [i.split() for i in status_list if 'ssh' in i]
tunnels = [] tunnels = []
for con in list: for con in list:
# local infos # local infos
local = con[3].split(':') local = con[3].split(':')
local_addr = local[0] local_addr = local[0]
local_port = int(local[1]) local_port = int(local[1])
# foreign infos # foreign infos
foreign = con[4].split(':') foreign = con[4].split(':')
foreign_addr = foreign[0] foreign_addr = foreign[0]
foreign_port = int(foreign[1]) foreign_port = int(foreign[1])
status = con[5] status = con[5]
sshpid = int( con[6].split('/')[0] ) sshpid = int( con[6].split('/')[0] )
# ssh cmd line, got from /proc # ssh cmd line, got from /proc
f = open( '/proc/' + str(sshpid) + '/cmdline' ) f = open( '/proc/' + str(sshpid) + '/cmdline' )
cmd = f.readlines()[0] cmd = f.readlines()[0]
# if not an ssh tunnel command # if not an ssh tunnel command
if ('-L' not in cmd) and (':' not in cmd): if ('-L' not in cmd) and (':' not in cmd):
# do not list it # do not list it
continue continue
f.close() f.close()
# autossh parent process # autossh parent process
f = open( '/proc/' + str(sshpid) + '/status' ) f = open( '/proc/' + str(sshpid) + '/status' )
# filter the parent pid # filter the parent pid
lpid = [i for i in f.readlines() if 'PPid' in i] lpid = [i for i in f.readlines() if 'PPid' in i]
f.close() f.close()
# parsing # parsing
ppid = int(lpid[0].split(':')[1].strip()) ppid = int(lpid[0].split(':')[1].strip())
# command line of the parent process # command line of the parent process
f = open( '/proc/' + str(ppid) + '/cmdline' ) f = open( '/proc/' + str(ppid) + '/cmdline' )
# exclude the port # exclude the port
autohost = f.readlines()[0].split(':')[1] autohost = f.readlines()[0].split(':')[1]
f.close() f.close()
# instanciation # instanciation
tunnels += [ SSHTunnel( local_addr, local_port, foreign_addr, foreign_port, autohost, status, sshpid, ppid ) ] tunnels += [ SSHTunnel( local_addr, local_port, foreign_addr, foreign_port, autohost, status, sshpid, ppid ) ]
return tunnels 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:
for i in autosshs: for i in autosshs:
if i['pid'] == t['autossh_pid']: if i['pid'] == t['autossh_pid']:
# add to the list of tunnels of the AutoSSHInstance instance # add to the list of tunnels of the AutoSSHInstance instance
i['tunnels'] += [t] i['tunnels'] += [t]
return autosshs return autosshs
################################################################################################# #################################################################################################
@ -268,318 +268,318 @@ import time
import signal import signal
class monitorCurses: class monitorCurses:
"""Textual user interface to display up-to-date informations about current tunnels""" """Textual user interface to display up-to-date informations about current tunnels"""
def __init__(self, scr): def __init__(self, scr):
# curses screen # curses screen
self.scr = scr self.scr = scr
# tunnels monitor # tunnels monitor
self.tm = AutoSSHTunnelMonitor() self.tm = AutoSSHTunnelMonitor()
# selected line # selected line
self.cur_line = -1 self.cur_line = -1
# selected pid # selected pid
self.cur_pid = -1 self.cur_pid = -1
# switch to show only autoss processes (False) or ssh connections also (True) # switch to show only autoss processes (False) or ssh connections also (True)
self.show_tunnels = False self.show_tunnels = False
self.update_delay = 1 # seconds of delay between two updates self.update_delay = 1 # seconds of delay between two updates
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, '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, '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}
def __call__(self): def __call__(self):
"""Start the interface""" """Start the interface"""
self.scr.clear() # clear all self.scr.clear() # clear all
self.scr.nodelay(1) # non-bloking getch self.scr.nodelay(1) # non-bloking getch
# first display # first display
self.display() self.display()
# first update counter # first update counter
last_update = time.clock() last_update = time.clock()
# infinit loop # infinit loop
while(1): while(1):
# wait some time # wait some time
# necessary to not overload the system with unnecessary calls # necessary to not overload the system with unnecessary calls
time.sleep( self.ui_delay ) time.sleep( self.ui_delay )
# if its time to update # if its time to update
if time.time() > last_update + self.update_delay: if time.time() > last_update + self.update_delay:
self.tm.update() self.tm.update()
# reset the counter # reset the counter
last_update = time.time() last_update = time.time()
kc = self.scr.getch() # keycode kc = self.scr.getch() # keycode
if kc != -1: # if keypress if kc != -1: # if keypress
pass pass
if 0 < kc < 256: # if ascii key if 0 < kc < 256: # if ascii key
# ascii character from the keycode # ascii character from the keycode
ch = chr(kc) ch = chr(kc)
# Quit # Quit
if ch in 'Qq': if ch in 'Qq':
break break
# Reload related autossh tunnels # Reload related autossh tunnels
elif ch in 'rR': elif ch in 'rR':
# if a pid is selected # if a pid is selected
if self.cur_pid != -1: if self.cur_pid != -1:
# send the SIGUSR1 signal # send the SIGUSR1 signal
# autossh performs a reload of existing tunnels that it manages # autossh performs a reload of existing tunnels that it manages
os.kill( self.cur_pid, signal.SIGUSR1 ) os.kill( self.cur_pid, signal.SIGUSR1 )
# Kill autossh process # Kill autossh process
elif ch in 'kK': elif ch in 'kK':
if self.cur_pid != -1: if self.cur_pid != -1:
# send a SIGKILL # send a SIGKILL
# the related process is stopped # the related process is stopped
# FIXME SIGTERM or SIGKILL ? # FIXME SIGTERM or SIGKILL ?
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': elif ch in 'tT':
self.show_tunnels = not self.show_tunnels self.show_tunnels = not self.show_tunnels
# key down # key down
elif kc == curses.KEY_DOWN: elif kc == curses.KEY_DOWN:
# if not the end of the list # if not the end of the list
if self.cur_line < len(self.tm)-1: if self.cur_line < len(self.tm)-1:
self.cur_line += 1 self.cur_line += 1
# get the pid # get the pid
self.cur_pid = int(self.tm[self.cur_line]['pid']) self.cur_pid = int(self.tm[self.cur_line]['pid'])
# key up # key up
elif kc == curses.KEY_UP: elif kc == curses.KEY_UP:
if self.cur_line > -1: if self.cur_line > -1:
self.cur_line -= 1 self.cur_line -= 1
self.cur_pid = int(self.tm[self.cur_line]['pid']) self.cur_pid = int(self.tm[self.cur_line]['pid'])
else: else:
# do nothing and wait until the next refresh # do nothing and wait until the next refresh
pass pass
# update the display # update the display
self.display() self.display()
# force a screen refresh # force a screen refresh
self.scr.refresh() self.scr.refresh()
def display(self): def display(self):
"""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) ) self.scr.addstr(0,0, "[R]:reload autossh [K]:kill autossh [Q]:quit [T]:show tunnels connections\n", curses.color_pair(4) )
self.scr.clrtoeol() self.scr.clrtoeol()
# Second line # Second line
self.scr.addstr( "Active AutoSSH instances: ", curses.color_pair(6) ) self.scr.addstr( "Active AutoSSH instances: ", curses.color_pair(6) )
self.scr.addstr( str( len(self.tm) ), curses.color_pair(1) ) self.scr.addstr( str( len(self.tm) ), curses.color_pair(1) )
self.scr.addstr( '\n', curses.color_pair(1) ) self.scr.addstr( '\n', curses.color_pair(1) )
self.scr.clrtoeol() self.scr.clrtoeol()
# if no line is selected # if no line is selected
color = 0 color = 0
if self.cur_line==-1: if self.cur_line==-1:
# selected color for the header # selected color for the header
color = 9 color = 9
self.cur_pid = -1 self.cur_pid = -1
# header line # header line
self.scr.addstr( "PID \tINPORT\tHOST \tOUTPORT\tCONNECTIONS", curses.color_pair(color) ) self.scr.addstr( "PID \tINPORT\tHOST \tOUTPORT\tCONNECTIONS", 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
for l in xrange(len(self.tm)): for l in xrange(len(self.tm)):
# add a line for the l-th autossh process # add a line for the l-th autossh process
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:
self.add_tunnel( l ) self.add_tunnel( l )
self.scr.clrtobot() self.scr.clrtobot()
def add_tunnel(self, line ): def add_tunnel(self, line ):
"""Add lines for each connections related to the l-th autossh process""" """Add lines for each connections related to the l-th autossh process"""
colors = self.colors_ssh colors = self.colors_ssh
# for each connections related to te line-th autossh process # for each connections related to te line-th autossh process
for t in self.tm[line]['tunnels']: for t in self.tm[line]['tunnels']:
self.scr.addstr( '\n\t* ' ) self.scr.addstr( '\n\t* ' )
self.scr.addstr( str( t['ssh_pid'] ), curses.color_pair(colors['ssh_pid'] ) ) self.scr.addstr( str( t['ssh_pid'] ), curses.color_pair(colors['ssh_pid'] ) )
self.scr.addstr( '\t' ) self.scr.addstr( '\t' )
self.scr.addstr( str( t['local_address'] ) , curses.color_pair(colors['local_address'] )) self.scr.addstr( str( t['local_address'] ) , curses.color_pair(colors['local_address'] ))
self.scr.addstr( ':' ) self.scr.addstr( ':' )
self.scr.addstr( str( t['local_port'] ) , curses.color_pair(colors['local_port'] )) self.scr.addstr( str( t['local_port'] ) , curses.color_pair(colors['local_port'] ))
self.scr.addstr( '->' ) self.scr.addstr( '->' )
self.scr.addstr( str( t['foreign_address'] ) , curses.color_pair(colors['foreign_address'] )) self.scr.addstr( str( t['foreign_address'] ) , curses.color_pair(colors['foreign_address'] ))
self.scr.addstr( ':' ) self.scr.addstr( ':' )
self.scr.addstr( str( t['foreign_port'] ) , curses.color_pair(colors['foreign_port'] )) self.scr.addstr( str( t['foreign_port'] ) , curses.color_pair(colors['foreign_port'] ))
self.scr.addstr( '\t' ) self.scr.addstr( '\t' )
color = self.colors_ssh['status'] color = self.colors_ssh['status']
# if the connections is established # if the connections is established
# TODO avoid hard-coded constants # TODO avoid hard-coded constants
if t['status'] != 'ESTABLISHED': if t['status'] != 'ESTABLISHED':
color = self.colors_ssh['status_out'] color = self.colors_ssh['status_out']
self.scr.addstr( str( t['status'] ), curses.color_pair( color ) ) self.scr.addstr( str( t['status'] ), curses.color_pair( color ) )
self.scr.clrtoeol() self.scr.clrtoeol()
def add_autossh(self, line): def add_autossh(self, line):
"""Add line corresponding to the line-th autossh process""" """Add line corresponding to the line-th autossh process"""
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('target_host', line) self.add_autossh_info('target_host', line)
self.add_autossh_info('foreign_port', line) self.add_autossh_info('foreign_port', line)
nb = len(self.tm[line]['tunnels'] ) nb = len(self.tm[line]['tunnels'] )
if nb > 0: if nb > 0:
# for each connection related to this process # for each connection related to this process
for i in self.tm[line]['tunnels']: for i in self.tm[line]['tunnels']:
# add a vertical bar | # add a vertical bar |
# the color change according to the status of the connection # the color change according to the status of the connection
if i['status'] == 'ESTABLISHED': if i['status'] == 'ESTABLISHED':
self.scr.addstr( '|', curses.color_pair(self.colors_ssh['status']) ) self.scr.addstr( '|', curses.color_pair(self.colors_ssh['status']) )
else:
self.scr.addstr( '|', curses.color_pair(self.colors_ssh['status_out']) )
else: else:
self.scr.addstr( '|', curses.color_pair(self.colors_ssh['status_out']) ) # if there is no connection, display a "None"
self.scr.addstr( 'None', curses.color_pair(self.colors_autossh['tunnels_nb_none']) )
else: self.scr.clrtoeol()
# if there is no connection, display a "None"
self.scr.addstr( 'None', curses.color_pair(self.colors_autossh['tunnels_nb_none']) )
self.scr.clrtoeol()
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"""
colors = self.colors_autossh colors = self.colors_autossh
# if the line is selected # if the line is selected
if self.cur_line == line: if self.cur_line == line:
# set the color to the highlight one # set the color to the highlight one
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':
# 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]
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."""
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")
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")
(options, args) = parser.parse_args() (options, args) = parser.parse_args()
# unfortunately, options class has no __len__ method in python 2.4.3 (bug?) # unfortunately, options class has no __len__ method in python 2.4.3 (bug?)
#if len(options) > 1: #if len(options) > 1:
# parser.error("options are mutually exclusive") # parser.error("options are mutually exclusive")
if options.curses: if options.curses:
import curses import curses
import traceback import traceback
try: try:
scr = curses.initscr() scr = curses.initscr()
curses.start_color() curses.start_color()
# 0:black, 1:red, 2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, 7:white # 0:black, 1:red, 2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, 7:white
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)
curses.init_pair(3, curses.COLOR_YELLOW, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_YELLOW, curses.COLOR_BLACK)
curses.init_pair(4, curses.COLOR_BLUE, curses.COLOR_BLACK) curses.init_pair(4, curses.COLOR_BLUE, curses.COLOR_BLACK)
curses.init_pair(5, curses.COLOR_MAGENTA, curses.COLOR_BLACK) curses.init_pair(5, curses.COLOR_MAGENTA, curses.COLOR_BLACK)
curses.init_pair(6, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(6, curses.COLOR_CYAN, curses.COLOR_BLACK)
curses.init_pair(7, curses.COLOR_WHITE, curses.COLOR_BLACK) curses.init_pair(7, curses.COLOR_WHITE, curses.COLOR_BLACK)
curses.init_pair(8, curses.COLOR_WHITE, curses.COLOR_GREEN) curses.init_pair(8, curses.COLOR_WHITE, curses.COLOR_GREEN)
curses.init_pair(9, curses.COLOR_WHITE, curses.COLOR_BLUE) curses.init_pair(9, curses.COLOR_WHITE, curses.COLOR_BLUE)
curses.noecho() curses.noecho()
curses.cbreak() curses.cbreak()
scr.keypad(1) scr.keypad(1)
# create the monitor # create the monitor
mc = monitorCurses( scr ) mc = monitorCurses( scr )
# call the monitor # call the monitor
mc() mc()
scr.keypad(0) scr.keypad(0)
curses.echo() curses.echo()
curses.nocbreak() curses.nocbreak()
curses.endwin() curses.endwin()
except: except:
# end cleanly # end cleanly
scr.keypad(0) scr.keypad(0)
curses.echo() curses.echo()
curses.nocbreak() curses.nocbreak()
curses.endwin() curses.endwin()
# print the traceback # print the traceback
traceback.print_exc() traceback.print_exc()
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
con = tm.get_connections() con = tm.get_connections()
for c in con: for c in con:
print con print con
elif options.autossh: elif options.autossh:
tm = AutoSSHTunnelMonitor() tm = AutoSSHTunnelMonitor()
# do not call update() bu only get autossh processes # do not call update() bu only get autossh processes
auto = tm.get_autossh_instances() auto = tm.get_autossh_instances()
for i in auto: for i in auto:
print auto print auto
else: else:
tm = AutoSSHTunnelMonitor() tm = AutoSSHTunnelMonitor()
# call update # call update
tm.update() tm.update()
# call the default __repr__ # call the default __repr__
print tm print tm
# #