Handle ipv6, fix curses itf, add logging

IPv6 addresses where incorrectly parsed.
The curses interface was crashing.
Add logging options to debug curses.
This commit is contained in:
Johann Dreo 2016-11-30 18:15:12 +01:00
commit 9b0833f65c

View file

@ -17,7 +17,7 @@
# 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 : nojhan <nojhan@nojhan.net>
# #
################################################################################################# #################################################################################################
@ -26,6 +26,7 @@
import os import os
import subprocess import subprocess
import logging
# fort sorting dictionaries easily # fort sorting dictionaries easily
from operator import itemgetter from operator import itemgetter
@ -59,7 +60,7 @@ class SSHTunnel(dict):
) )
class AutoSSHInstance(dict): class AutoSSHprocess(dict):
"""A dictionary that stores an autossh process""" """A dictionary that stores an autossh process"""
def __init__(self, pid = 0, local_port = 0, via_host="Unknown", target_host = "Unknown",foreign_port = 0): def __init__(self, pid = 0, local_port = 0, via_host="Unknown", target_host = "Unknown",foreign_port = 0):
@ -109,11 +110,16 @@ class AutoSSHTunnelMonitor(list):
"""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()
logging.debug("Autossh processes: %s" % autosshs)
# ssh connections related to a tunnel # ssh connections related to a tunnel
connections = self.get_connections() connections = self.get_connections()
logging.debug("SSH connections related to a tunnel: %s" % connections)
# bind existing connections to autossh processes # Bind existing connections to autossh processes.
# Thus the instance is a list of AutoSSHinstance instances,
# each of those instances having a 'tunnels' key,
# hosting the corresponding list of tunnel connections.
self[:] = self.bind_tunnels(autosshs, connections) self[:] = self.bind_tunnels(autosshs, connections)
# sort on a given key # sort on a given key
@ -141,8 +147,6 @@ 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"""
@ -158,16 +162,18 @@ class AutoSSHTunnelMonitor(list):
# 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]
logging.debug("Processes containing 'autossh': %s" % status_list)
# 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] cmds = [i.split() for i in status_list if '-L' in i]
autosshs = [] autosshs = []
for cmd in list: for cmd in cmds:
# 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(':')
logging.debug("Split around -L: %s" % args)
pid = int(cmd[0]) pid = int(cmd[0])
local_port = int(args[0]) local_port = int(args[0])
@ -182,12 +188,26 @@ class AutoSSHTunnelMonitor(list):
break break
auto = AutoSSHInstance( pid, local_port, via_host, target_host, foreign_port ) auto = AutoSSHprocess( pid, local_port, via_host, target_host, foreign_port )
logging.debug("Add AutoSSHprocess: %s" % auto)
autosshs += [auto] autosshs.append( auto )
return autosshs return autosshs
def parse_addr_port(self, addr_port):
if len(addr_port) == 2: # ipv4
addr = addr_port[0]
logging.debug("IPv4 address: %s" % addr)
port = int(addr_port[1])
logging.debug("IPv4 port: %s" % port)
else: # ipv6
addr = ":".join(addr_port[:-1])
logging.debug("IPv6 address: %s" % addr)
port = int(addr_port[-1])
logging.debug("IPv6 port: %s" % port)
return addr,port
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"""
@ -200,37 +220,45 @@ class AutoSSHTunnelMonitor(list):
status = (p.stdin, p.stdout, p.stderr) status = (p.stdin, p.stdout, p.stderr)
status_list = status[1].readlines() status_list = status[1].readlines()
logging.debug("%i active connections" % len(status_list))
list = [i.split() for i in status_list if 'ssh' in i] cons = [i.split() for i in status_list if 'ssh' in i]
tunnels = [] tunnels = []
for con in list: for con in cons:
logging.debug("Candidate connection: %s" % con)
# netstat format:
# Proto Recv-Q Send-Q Adresse locale Adresse distante Etat PID/Program name
# local infos # local infos
local = con[3].split(':') local = con[3].split(':')
local_addr = local[0] logging.debug("local infos: %s" % local)
local_port = int(local[1]) local_addr, local_port = self.parse_addr_port(local)
# foreign infos # foreign infos
foreign = con[4].split(':') foreign = con[4].split(':')
foreign_addr = foreign[0] foreign_addr, foreign_port = self.parse_addr_port(foreign)
foreign_port = int(foreign[1])
status = con[5] status = con[5]
logging.debug("Connection status: %s" % status)
sshpid = int( con[6].split('/')[0] ) sshpid = int( con[6].split('/')[0] )
logging.debug("SSH PID: %s" % sshpid)
# 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]
logging.debug("SSH command: %s" % cmd)
# 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
logging.debug("Not a tunnel command")
continue continue
f.close() f.close()
logging.debug("Is a tunnel command")
# autossh parent process # autossh parent process
f = open( '/proc/' + str(sshpid) + '/status' ) f = open( '/proc/' + str(sshpid) + '/status' )
@ -252,7 +280,7 @@ class AutoSSHTunnelMonitor(list):
f.close() f.close()
# instanciation # instanciation
tunnels += [ SSHTunnel( local_addr, local_port, foreign_addr, foreign_port, autohost, status, sshpid, ppid ) ] tunnels.append( SSHTunnel( local_addr, local_port, foreign_addr, foreign_port, autohost, status, sshpid, ppid ) )
return tunnels return tunnels
@ -262,10 +290,10 @@ class AutoSSHTunnelMonitor(list):
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 AutoSSHprocess instance
i['tunnels'] += [t] i['tunnels'].append( t )
return tunnels return autosshs
################################################################################################# #################################################################################################
@ -315,6 +343,7 @@ class monitorCurses:
# first update counter # first update counter
last_update = time.clock() last_update = time.clock()
last_state = None
# infinite loop # infinite loop
while(1): while(1):
@ -329,6 +358,15 @@ class monitorCurses:
# reset the counter # reset the counter
last_update = time.time() last_update = time.time()
state = "%s" % self.tm
if state != last_state:
logging.debug("----- Time of screen update: %s -----" % time.time())
logging.debug("State of tunnels:\n%s" % self.tm)
last_state = state
else:
logging.debug('.')
kc = self.scr.getch() # keycode kc = self.scr.getch() # keycode
if kc != -1: # if keypress if kc != -1: # if keypress
@ -342,31 +380,38 @@ class monitorCurses:
# Quit # Quit
if ch in 'Qq': if ch in 'Qq':
logging.debug("Key pushed: Q")
break break
# Reload related autossh tunnels # Reload related autossh tunnels
elif ch in 'rR': elif ch in 'rR':
logging.debug("Key pushed: R")
# 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
logging.debug("SIGUSR1 on PID: %i" % self.cur_pid)
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':
logging.debug("Key pushed: K")
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 ?
logging.debug("SIGKILL on PID: %i" % self.cur_pid)
os.kill( self.cur_pid, signal.SIGKILL ) os.kill( self.cur_pid, signal.SIGKILL )
# Switch to show ssh connections # Switch to show ssh connections
# only available for root # only available for root
elif ch in 'tT' and os.getuid() == 0: elif ch in 'tT' and os.getuid() == 0:
logging.debug("Key pushed: T")
self.show_tunnels = not self.show_tunnels self.show_tunnels = not self.show_tunnels
# key down # key pushed
elif kc == curses.KEY_DOWN: elif kc == curses.KEY_DOWN:
logging.debug("Key pushed: downed")
# 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
@ -375,6 +420,7 @@ class monitorCurses:
# key up # key up
elif kc == curses.KEY_UP: elif kc == curses.KEY_UP:
logging.debug("Key pushed: 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'])
@ -493,9 +539,6 @@ class monitorCurses:
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"""
@ -514,6 +557,8 @@ 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
@ -525,21 +570,57 @@ if __name__ == "__main__":
Version 0.3""" Version 0.3"""
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",
help="start the user interface in text mode") action="store_true", default=False,
parser.add_option("-n", "--connections", action="store_true", dest="connections", default=False, help="Start the user interface in text mode.")
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("-n", "--connections",
help="display only the list of autossh processes") action="store_true", default=False,
help="Display only SSH connections related to a tunnel (only available as root).")
parser.add_option("-a", "--autossh",
action="store_true", default=False,
help="Display only the list of autossh processes.")
LOG_LEVELS = {'error' : logging.ERROR,
'warning' : logging.WARNING,
'debug' : logging.DEBUG}
parser.add_option('-l', '--log-level', choices=list(LOG_LEVELS), default='error', metavar='LEVEL',
help='Log level (%s), default: %s.' % (", ".join(LOG_LEVELS), 'error') )
parser.add_option('-f', '--log-file', default=None, metavar='FILE',
help="Log to this file, default to standard output. \
If not set, asking for the curses interface automatically set logging to the \"ereshkigal.log\" file.")
(options, args) = parser.parse_args() (options, args) = parser.parse_args()
print(options)
logmsg = "----- Started Ereshkigal -----"
if options.log_file:
logfile = options.log_file
logging.basicConfig(filename=logfile, level=LOG_LEVELS[options.log_level])
logging.debug(logmsg)
logging.debug("Log in %s" % logfile)
else:
if options.curses:
logging.basicConfig(filename='ereshkigal.log', level=LOG_LEVELS[options.log_level])
logging.debug(logmsg)
logging.debug("Log in ereshkigal.log")
else:
logging.basicConfig(level=LOG_LEVELS[options.log_level])
logging.debug(logmsg)
logging.debug("Log to stdout")
logging.debug("Asked for: %s" % options)
# 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:
logging.debug("Entering curses mode")
import curses import curses
import traceback import traceback
@ -584,30 +665,34 @@ if __name__ == "__main__":
elif options.connections: elif options.connections:
logging.debug("Entering connections mode")
tm = AutoSSHTunnelMonitor() tm = AutoSSHTunnelMonitor()
# do not call update() but only get connections # do not call update() but only get connections
logging.debug("UID: %i." % os.geteuid())
if os.geteuid() == 0: 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: else:
print "Error: only root can see SSH tunnels connections" logging.error("Only root can see SSH tunnels connections.")
elif options.autossh: elif options.autossh:
logging.debug("Entering autossh mode")
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:
logging.debug("Entering default mode")
tm = AutoSSHTunnelMonitor() tm = AutoSSHTunnelMonitor()
# call update # call update
tm.update() tm.update()
# call the default __repr__ # call the default __repr__
print tm print(tm)
# #