solve a few bug
This commit is contained in:
parent
d6a3dbd75b
commit
b5b6d282fb
1 changed files with 137 additions and 142 deletions
111
tunnelmon.py
111
tunnelmon.py
|
|
@ -1,4 +1,4 @@
|
|||
#!/usr/bin/python3
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# Ereshkigal is an AutoSSH tunnel monitor
|
||||
|
|
@ -24,6 +24,9 @@
|
|||
# CORE
|
||||
#################################################################################################
|
||||
|
||||
import signal
|
||||
import time
|
||||
import curses
|
||||
import os
|
||||
import subprocess
|
||||
import logging
|
||||
|
|
@ -31,19 +34,20 @@ import psutil
|
|||
import socket
|
||||
import re
|
||||
import collections
|
||||
import itertools
|
||||
|
||||
|
||||
class Tunnel:
|
||||
def __init__(self, ssh_pid=None, in_port=None, via_host=None, target_host=None, out_port=None):
|
||||
# assert(ssh_pid != None)
|
||||
# assert ssh_pid is not None
|
||||
self.ssh_pid = ssh_pid
|
||||
assert(in_port!=None)
|
||||
assert in_port is not None
|
||||
self.in_port = in_port
|
||||
assert(via_host!=None)
|
||||
assert via_host is not None
|
||||
self.via_host = via_host
|
||||
assert(target_host!=None)
|
||||
assert target_host is not None
|
||||
self.target_host = target_host
|
||||
assert(out_port!=None)
|
||||
assert out_port is not None
|
||||
self.out_port = out_port
|
||||
|
||||
self.connections = []
|
||||
|
|
@ -70,7 +74,7 @@ class Tunnel:
|
|||
class AutoTunnel(Tunnel):
|
||||
def __init__(self, autossh_pid=None, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
assert(autossh_pid!=None)
|
||||
assert autossh_pid is not None
|
||||
self.autossh_pid = autossh_pid
|
||||
|
||||
def repr_tunnel(self):
|
||||
|
|
@ -94,15 +98,15 @@ class Connection:
|
|||
status=None, family=None):
|
||||
|
||||
# informations available with netstat
|
||||
assert(local_address!=None)
|
||||
assert local_address is not None
|
||||
self.local_address = local_address
|
||||
assert(in_port!=None)
|
||||
assert in_port is not None
|
||||
self.in_port = in_port
|
||||
self.foreign_address = foreign_address
|
||||
self.out_port = out_port
|
||||
assert(status!=None)
|
||||
assert status is not None
|
||||
self.status = status
|
||||
assert(family!=None)
|
||||
assert family is not None
|
||||
self.family = family
|
||||
|
||||
self.family_rep = {socket.AddressFamily.AF_INET: "INET", socket.AddressFamily.AF_INET6: "INET6", socket.AddressFamily.AF_UNIX: "UNIX"}
|
||||
|
|
@ -142,39 +146,49 @@ class TunnelsParser:
|
|||
# only a list of connections OR autossh processes
|
||||
# self.update()
|
||||
|
||||
self.re_forwarding = re.compile(r"-L(\d+):(.+):(\d+)")
|
||||
self.re_forwarding = re.compile(r"-L\s*(\d+):(.*):(\d+)")
|
||||
|
||||
self.header = 'TYPE\tSSH_PID\tIN_PORT\tVIA_HOST\tTARGET_HOST\tOUT_PORT'
|
||||
|
||||
|
||||
def get_tunnel(self, pos):
|
||||
pid = list(self.tunnels.keys())[pos]
|
||||
return self.tunnels[pid]
|
||||
|
||||
|
||||
def parse(self, cmd):
|
||||
cmdline = " ".join(cmd)
|
||||
|
||||
logging.debug('autossh cmd line:', cmdline)
|
||||
logging.debug('forwarding regexp:', self.re_forwarding)
|
||||
logging.debug('autossh cmd line: %s', cmdline)
|
||||
logging.debug('forwarding regexp: %s', self.re_forwarding)
|
||||
match = self.re_forwarding.findall(cmdline)
|
||||
logging.debug(match)
|
||||
if match:
|
||||
assert(len(match)==1)
|
||||
assert len(match) == 1
|
||||
in_port, target_host, out_port = match[0]
|
||||
logging.debug("matches: ", match)
|
||||
logging.debug("matches: %s", match)
|
||||
else:
|
||||
raise ValueError("is not a ssh tunnel")
|
||||
|
||||
# Find the hostname on wich the tunnel is built.
|
||||
via_host = "unknown"
|
||||
# Search backward and take the first parameter argument.
|
||||
# FIXME this is an ugly hack
|
||||
for i in range( len(cmd)-1,0,-1 ):
|
||||
if cmd[i][0] != '-':
|
||||
i = 1
|
||||
while i < len(cmd):
|
||||
logging.debug("ici: %i %s", i, cmd[i])
|
||||
if cmd[i][0] == '-':
|
||||
if cmd[i][1] in '46AaCfGgKkMNnqsTtVvXxYy':
|
||||
# flag without argument
|
||||
pass
|
||||
elif len(cmd[i]) == 2: # the argument is likely the next one
|
||||
if (i < len(cmd) - 1) and (cmd[i + 1][0] != '-'): # not another flag (this should always be true)
|
||||
i += 1 # skip the argument
|
||||
# skip the argument
|
||||
i += 1
|
||||
else:
|
||||
via_host = cmd[i]
|
||||
break
|
||||
|
||||
return (int(in_port), via_host, target_host, int(out_port))
|
||||
|
||||
return int(in_port), via_host, target_host, int(out_port)
|
||||
|
||||
def update(self):
|
||||
"""Gather and parse informations from the operating system"""
|
||||
|
|
@ -191,8 +205,11 @@ class TunnelsParser:
|
|||
else:
|
||||
if process['name'] == 'ssh':
|
||||
logging.debug(process)
|
||||
try:
|
||||
in_port, via_host, target_host, out_port = self.parse(cmd)
|
||||
logging.debug(in_port, via_host, target_host, out_port)
|
||||
except ValueError:
|
||||
continue
|
||||
logging.debug("%s %s %s %s", in_port, via_host, target_host, out_port)
|
||||
|
||||
# Check if this ssh tunnel is managed by autossh.
|
||||
parent = psutil.Process(process['ppid'])
|
||||
|
|
@ -218,7 +235,6 @@ class TunnelsParser:
|
|||
|
||||
logging.debug(self.tunnels)
|
||||
|
||||
|
||||
def __repr__(self):
|
||||
reps = [self.header]
|
||||
for t in self.tunnels:
|
||||
|
|
@ -226,14 +242,10 @@ class TunnelsParser:
|
|||
return "\n".join(reps)
|
||||
|
||||
|
||||
|
||||
#################################################################################################
|
||||
# INTERFACES
|
||||
#################################################################################################
|
||||
|
||||
import curses
|
||||
import time
|
||||
import signal
|
||||
|
||||
class CursesMonitor:
|
||||
"""Textual user interface to display up-to-date informations about current tunnels"""
|
||||
|
|
@ -260,9 +272,12 @@ class CursesMonitor:
|
|||
|
||||
# colors
|
||||
# FIXME different colors for different types of tunnels (auto or raw)
|
||||
self.colors_tunnel = {'kind_auto':4, 'kind_raw':5, 'ssh_pid':0, 'in_port':3, 'via_host':2, 'target_host':2, 'out_port':3, 'tunnels_nb':4, 'tunnels_nb_none':1}
|
||||
self.colors_highlight = {'kind_auto':9, 'kind_raw':9, 'ssh_pid':9, 'in_port':9, 'via_host':9, 'target_host':9, 'out_port':9, 'tunnels_nb':9, 'tunnels_nb_none':9}
|
||||
self.colors_connection = {'ssh_pid':0, 'autossh_pid':0, 'status':4, 'status_out':1, 'local_address':2, 'in_port':3, 'foreign_address':2, 'out_port':3}
|
||||
self.colors_tunnel = {'kind_auto': 4, 'kind_raw': 5, 'ssh_pid': 0, 'in_port': 3,
|
||||
'via_host': 2, 'target_host': 2, 'out_port': 3, 'tunnels_nb': 4, 'tunnels_nb_none': 1}
|
||||
self.colors_highlight = {'kind_auto': 9, 'kind_raw': 9, 'ssh_pid': 9, 'in_port': 9,
|
||||
'via_host': 9, 'target_host': 9, 'out_port': 9, 'tunnels_nb': 9, 'tunnels_nb_none': 9}
|
||||
self.colors_connection = {'ssh_pid': 0, 'autossh_pid': 0, 'status': 4, 'status_out': 1,
|
||||
'local_address': 2, 'in_port': 3, 'foreign_address': 2, 'out_port': 3}
|
||||
|
||||
self.header = ("TYPE", "SSHPID", "INPORT", "VIA", "TARGET", "OUTPORT")
|
||||
|
||||
|
|
@ -273,7 +288,6 @@ class CursesMonitor:
|
|||
logging.debug("Key pushed: Q")
|
||||
return False
|
||||
|
||||
|
||||
def do_R(self):
|
||||
"""Reload autossh tunnel"""
|
||||
logging.debug("Waited: %s" % self.log_ticks)
|
||||
|
|
@ -290,7 +304,6 @@ class CursesMonitor:
|
|||
logging.debug("Cannot reload a RAW tunnel")
|
||||
return True
|
||||
|
||||
|
||||
def do_C(self):
|
||||
"""Close tunnel"""
|
||||
logging.debug("Waited: %s" % self.log_ticks)
|
||||
|
|
@ -314,12 +327,11 @@ class CursesMonitor:
|
|||
os.kill(tunnel.ssh_pid, signal.SIGKILL)
|
||||
except OSError:
|
||||
logging.error("No such process: %i" % tunnel.ssh_pid)
|
||||
self.cur_line = -1
|
||||
self.cur_line -= 1
|
||||
self.cur_pid = -1
|
||||
# FIXME update cur_pid or get rid of it everywhere
|
||||
return True
|
||||
|
||||
|
||||
def do_N(self):
|
||||
"""Show connections"""
|
||||
logging.debug("Waited: %s" % self.log_ticks)
|
||||
|
|
@ -328,7 +340,6 @@ class CursesMonitor:
|
|||
self.show_connections = not self.show_connections
|
||||
return True
|
||||
|
||||
|
||||
def do_258(self):
|
||||
"""Move down"""
|
||||
logging.debug("Waited: %s" % self.log_ticks)
|
||||
|
|
@ -344,7 +355,6 @@ class CursesMonitor:
|
|||
self.cur_pid = self.tp.get_tunnel(self.cur_line).ssh_pid
|
||||
return True
|
||||
|
||||
|
||||
def do_259(self):
|
||||
"""Move up"""
|
||||
logging.debug("Waited: %s" % self.log_ticks)
|
||||
|
|
@ -353,10 +363,9 @@ class CursesMonitor:
|
|||
if self.cur_line > -1:
|
||||
self.cur_line -= 1
|
||||
if self.cur_line > 0:
|
||||
self.cur_pid = self.tp.get_tunnel(self.cur_line).pid
|
||||
self.cur_pid = self.tp.get_tunnel(self.cur_line).ssh_pid
|
||||
return True
|
||||
|
||||
|
||||
def __call__(self):
|
||||
"""Start the interface"""
|
||||
|
||||
|
|
@ -395,7 +404,6 @@ class CursesMonitor:
|
|||
else:
|
||||
self.log_ticks += "."
|
||||
|
||||
|
||||
kc = self.scr.getch() # keycode
|
||||
|
||||
if kc != -1: # if keypress
|
||||
|
|
@ -425,20 +433,17 @@ class CursesMonitor:
|
|||
|
||||
# end of the loop
|
||||
|
||||
|
||||
def format(self):
|
||||
reps = [self.tp.tunnels[t].repr_tunnel() for t in self.tp.tunnels]
|
||||
tuns = [t.split() for t in reps]
|
||||
tuns.append(self.header)
|
||||
logging.debug(tuns)
|
||||
cols = zip(*tuns)
|
||||
cols = itertools.zip_longest(*tuns, fillvalue='')
|
||||
widths = [max(len(s) for s in col) for col in cols]
|
||||
logging.debug(widths)
|
||||
fmt = ['{{: <{}}}'.format(w) for w in widths]
|
||||
logging.debug(fmt)
|
||||
return fmt
|
||||
|
||||
|
||||
def display(self):
|
||||
"""Generate the interface screen"""
|
||||
|
||||
|
|
@ -490,7 +495,6 @@ class CursesMonitor:
|
|||
|
||||
self.scr.clrtobot()
|
||||
|
||||
|
||||
def add_connection(self, line):
|
||||
"""Add lines for each connections related to the l-th autossh process"""
|
||||
|
||||
|
|
@ -525,7 +529,6 @@ class CursesMonitor:
|
|||
|
||||
self.scr.clrtoeol()
|
||||
|
||||
|
||||
def add_tunnel(self, line):
|
||||
"""Add line corresponding to the line-th autossh process"""
|
||||
self.scr.addstr('\n')
|
||||
|
|
@ -566,7 +569,6 @@ class CursesMonitor:
|
|||
|
||||
self.scr.clrtoeol()
|
||||
|
||||
|
||||
def add_tunnel_info(self, key, line, col):
|
||||
"""Add an information of an autossh process, in the configured color"""
|
||||
|
||||
|
|
@ -584,7 +586,6 @@ class CursesMonitor:
|
|||
self.scr.addstr(' ', curses.color_pair(colors[key]))
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
from optparse import OptionParser
|
||||
|
|
@ -639,7 +640,7 @@ if __name__ == "__main__":
|
|||
logging.debug(logmsg)
|
||||
logging.debug("Log to stdout")
|
||||
|
||||
logging.debug("Asked for: %s" % asked_for)
|
||||
logging.debug("Asked for: %s", asked_for)
|
||||
|
||||
# unfortunately, asked_for class has no __len__ method in python 2.4.3 (bug?)
|
||||
# if len(asked_for) > 1:
|
||||
|
|
@ -650,18 +651,16 @@ if __name__ == "__main__":
|
|||
try:
|
||||
config.read(asked_for.config_file)
|
||||
except configparser.MissingSectionHeaderError:
|
||||
logging.error("'%s' contains no known configuration" % asked_for.config_file)
|
||||
logging.error("'%s' contains no known configuration", asked_for.config_file)
|
||||
else:
|
||||
try:
|
||||
config.read('~/.ereshkigal.conf')
|
||||
except configparser.MissingSectionHeaderError:
|
||||
logging.error("'%s' contains no known configuration" % asked_for.config_file)
|
||||
logging.error("'%s' contains no known configuration", asked_for.config_file)
|
||||
|
||||
# Load autossh instances by sections: [expected]
|
||||
# if config['expected']:
|
||||
|
||||
|
||||
|
||||
if asked_for.curses:
|
||||
logging.debug("Entering curses mode")
|
||||
import curses
|
||||
|
|
@ -706,13 +705,12 @@ if __name__ == "__main__":
|
|||
# print the traceback
|
||||
traceback.print_exc()
|
||||
|
||||
|
||||
elif asked_for.connections:
|
||||
logging.debug("Entering connections mode")
|
||||
tp = TunnelsParser()
|
||||
tp.update()
|
||||
# do not call update() but only get connections
|
||||
logging.debug("UID: %i." % os.geteuid())
|
||||
logging.debug("UID: %i.", os.geteuid())
|
||||
# if os.geteuid() == 0:
|
||||
for t in tp.tunnels:
|
||||
for c in tp.tunnels[t].connections:
|
||||
|
|
@ -721,7 +719,6 @@ if __name__ == "__main__":
|
|||
# else:
|
||||
# logging.error("Only root can see SSH tunnels connections.")
|
||||
|
||||
|
||||
elif asked_for.tunnels:
|
||||
logging.debug("Entering tunnel mode")
|
||||
tp = TunnelsParser()
|
||||
|
|
@ -731,7 +728,6 @@ if __name__ == "__main__":
|
|||
for t in tp.tunnels:
|
||||
print(tp.tunnels[t].repr_tunnel())
|
||||
|
||||
|
||||
else:
|
||||
logging.debug("Entering default mode")
|
||||
tp = TunnelsParser()
|
||||
|
|
@ -749,4 +745,3 @@ if __name__ == "__main__":
|
|||
#
|
||||
# http://en.wikipedia.org/wiki/Ereshkigal
|
||||
#
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue