Code Monkey home page Code Monkey logo

tunnelmon's Introduction

tunnelmon -- Monitor and manage autoSSH tunnels

SYNOPSIS

tunnelmon [-h]

tunnelmon [-c] [-n] [-u] [-l LEVEL] [-g FILE] [-s]

DESCRIPTION

tunnelmon is an autossh tunnel monitor. It gives a user interface to monitor existing SSH tunnel, and tunnels managed with autossh.

It can print the current state of your tunnels or display them in an interactive text-based interface.

tunnelmon is released under the GNU Public License v3.

Screenshot

INSTALLATION

tunnelmon targets Linux operating systems, and depends on:

  • openssh-client,
  • python version 3.8 at least, you may also need to install the following python modules (for example via pip, but you may use any other package management system going along with your installation):
    • psutils
    • curses

You may also want to install the recommend packages:

  • autossh

OPTIONS

Called without option,tunnelmon will print the current state of the autossh tunnels and exit.

  • -h, --help: Show a help message and exit

  • -c, --curses: Start the interactive user interface. Tunnels states will be updated regularly and you will be able to control them (see below).

  • -n, --connections: Display only SSH connections related to a tunnel.

  • -u, --tunnels: Only display the list of tunnels processes.

  • -l LEVEL, --log-level LEVEL: Control the verbosity of the logging, the greater, the more verbose. Available log levels are: error < warning < debug. Defaults to error, which only prints unrecoverable problems.

  • -g FILE, --log-file FILE: Log messages are written to the given FILE. Useful to debug the interactive interface. If not set, asking for the curses interface automatically set logging to the "tunnelmon.log" file.

  • -s, --log-sensitive: Allow sensitive information (hostnames, IPs, PIDs, etc.) into the logs.

INTERACTIVE INTERFACE

Keyboard commands:

  • and : Select a tunnel.
  • R: Reload the selected autossh instance (i.e. send a SIGUSR1, which is interpreted as a reload command by autossh).
  • C: Close the selected tunnel (i.e. send a SIGTERM).
  • N: Show the network connections related to each tunnel instances.
  • Q: Quit Tunnelmon.

DISPLAY

Tunnelmon displays a table where lines are [auto]ssh processes that sets up a tunnel. Columns of the table indicates:

  • TYPE: auto if the process is managed by autossh, ssh if it is a "raw" SSH tunnel;
  • FORWARD: the type of port forwarding method (either local, remote or dynamic, see the SSH manual for details);
  • SSHPID: the process identifier;
  • INPORT: the client port;
  • VIA: the client host;
  • TARGET: the host address;
  • OUTPORT: the host port.

The interactive interface adds a CONNECTIONS columns that displays one vertical bar for each connection set up by the tunnel.

If you ask for showing the connections list (typing N in the interactive interface, or not passing -u to the command line one), Tunnelmon will show indented lines with the type of the connection, its status and the related address:port informations.

In the interactive interface, different colors are used for:

  • the tunnel type,
  • the port forwarding methods,
  • privileged and unprivileged ports,
  • loopback, private and regular addresses.

SSH Tunnels in a nutshell

To open a tunnel to port 1234 of server through a host reached on port 4567:

ssh -N host -L4567:server:1234

You may add -f to run ssh in the background.

Autossh can restart tunnels for you, in case they crash:

autossh -f host -L4567:server:1234

tunnelmon's People

Contributors

ghislainp avatar nojhan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

tunnelmon's Issues

The interface doesn't show with tunnelmon -c

Describe the bug
WARNING:root:It's a bad idea to log to stdout while in the curses interface.

To Reproduce
Steps to reproduce the behavior:

  1. Execute tunnelmon from the command line with the -c option: tunnelmon -c

Expected behavior
To show an interactive interface

Desktop (please complete the following information):

  • OS: Ubuntu
  • Version 22.04.1 LTS

fails to detect a tunnel

First time attempting to use this tool, and its failing to detect a working tunnel:

[netllama@hal tunnelmon-1.0]$ ./tunnelmon.py 
TYPE	SSH_PID	IN_PORT	VIA_HOST	TARGET_HOST	OUT_PORT
[netllama@hal tunnelmon-1.0]$ ps -ef | grep autossh
root     1634439 1633647  0 16:14 pts/2    00:00:00 nedit /usr/lib/systemd/system/[email protected]
netllama 1638649       1  0 16:28 ?        00:00:00 /usr/bin/autossh -M 0 -o ExitOnForwardFailure=yes -NTR 2220:127.0.0.1:22 [email protected] /home/netllama/.ssh/id_ed25519

Dependencies: "psutil", and probably "pip"

Hi!

I downloaded your tunnelmon.py script
and tried to run it (KUbuntu 20.04 LTS); I got this error:

$ python3 tunnelmon.py 
Traceback (most recent call last):
  File "tunnelmon.py", line 33, in <module>
    import psutil
ModuleNotFoundError: No module named 'psutil'

I "fixed" the situtation by installing "pip" module to easily install module "psutil"

$> sudo apt install pip
$> python3 -m pip install psutil

As you may consider as relevant to add this in your README file
here I am reporting this issue :)

Thanks for the nice tool!

--
Mickaël Sibelle

Display the type of port forwarding

SSH can port forward either locally (with -L), remotely (-R) or "dynamically" (-D).
Tunnelmon should display this information somehow, like using ssh(R) in the type column, for example.

« Petite revue de code » — GuieA_7 @ linuxfr.org

# Petite revue de code

Posté par GuieA_7 (site Web personnel) le 20/08/22 à 13:18. Évalué à 10 (+10/-0).

Bonjour,

je ne vais pas faire une PR GitHub (je ne saurai pas tester que je n'ai rien cassé). Mais comme j'aime bien relire du Python, je me permets quelques petites remarques, parce que le code est plutôt de bonne facture.

À beaucoup d'endroits (pas partout) on trouve des logging.debug("Log in %s" % logfile) ; il est préférable d'écrire logging.debug("Log in %s", logfile) car l'interpolation de chaîne ne sera faite que si le message est affiché (le niveau est DEBUG ou moins dans cet exemple).

logging.debug("ici: %i %s", i, cmd[i]) j'imagine que le "ici" est un reliquat.

if type(tunnel) == AutoTunnel: je pense qu'un if isinstance(tunnel, AutoTunnel): est plus propre (même si au final tester les types c'est pas très élégant, et genre une méthode/propriété "is_auto", par exemple, serait plus appropriée je trouve).

if t.status != 'ESTABLISHED' and t.status != 'LISTEN': => if t.status in ('ESTABLISHED', 'LISTEN'):

Il y a beaucoup d'utilisation de eval() qui gagneraient à être remplacées par des getattr() ; outre le caractère sécurité, on évite aussi de reparser du code à chaque fois (eval() est vraiment à éviter ; je doute m'en être servi en presque 20 ans de Python).
Dans la mesure où Python 3.8 est requis, tu peux utiliser à moult endroits les f-strings qui sont vraiment super sympathiques.

Il y a beaucoup de double-recherches dans les dictionnaires, quand une recherche simple sera plus efficace et souvent plus compacte.

if forward in self.forwards:
    self.forward = self.forwards[forward]
else:
    self.forward = "unknown"

peut s'écrire simplement self.forward = self.forwards.get(forward, "unknown").

De la même manière le bout de code suivant est intéressant (car plusieurs améliorations sont possibles)

    def __repr__(self):
        reps = [self.header]
        for t in self.tunnels:
            reps.append(str(self.tunnels[t]))
        return "\n".join(reps)

On utilise .values() vu qu'on n'a pas besoin de la clé:

    def __repr__(self):
        reps = [self.header]
        for tunnel in self.tunnels.values():
            reps.append(str(tunnel))
        return "\n".join(reps)

On utilise .extend() et une generator expression pour éviter d'avoir N appels à append() tout en étant plus court:

    def __repr__(self):
        reps = [self.header]
        # Remarque 1: pas besoin de mettre une autre paire de parenthèses car le generator est le seul paramètre
        reps.extend(str(tunnel) for tunnel in self.tunnels.values())
        # Remarque 2: version alternative avec map()
        # reps.extend(map(str, self.tunnels.values()))

        return "\n".join(reps)

Avec les nouvelles fonctionnalités d'unpacking de Python 3, on arrive à ce résultat qui a un petit goût de programmation fonctionnelle plutôt cool:

    def __repr__(self):
        return "\n".join([self.header, *map(str, self.tunnels.values())])

if c.raddr:
    raddr, rport = c.raddr
else:
    raddr, rport = (None, None)

==> raddr, rport = c.raddr or (None, None)

En espérant avoir été utile.
Bon week-end !

Conversion to package

This is a very cool tool, and it solves an important problem for us.

I'd recommend it to all of my teammates if only it were a little easier to install -- ideally via pip or conda (or both).

Here is a guide for converting a python project into a package: https://towardsdatascience.com/how-to-convert-your-python-project-into-a-package-installable-through-pip-a2b36e8ace10

Then there are the official docs: https://packaging.python.org/en/latest/tutorials/packaging-projects/

I'd do this myself and open a PR except that I won't have the bandwidth for the next few weeks.

Also, there is a typo in the list of depenencies: psutils shoul be psutil. Fixing that would be a good start!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.