Script "nc-who" - similar to unix `who`, follow live who is logged in

  • Have you ever wanted to check who’s online right now, if there’s any suspicious movement happening on your cloud?

  • Similar to unix who, follow live who is logged in with

→ nc-who ←

I have completely reworked this script, which was originally created here

It has a completely revised output. Since it updates at an adjustable refresh rate with watch, the formatted output from mysql was no longer usable. The solution was to output as html and back with html2text and sed in a usable, nice and neat format.
Nextcloud All-in-One is supported, containerized solutions other than AIO are not (yet) supported

This tool is primarily intended for administrators of Nextcloud instances with many users. Of course, this is not intended for small servers used in familiary circles. But they can also want to take a look and then the tool is not far:

Restriction: only for MySQL/MariaDB Supported databases: MySQL/MariaDB, PostgreSQL

This script was created with → ebtb ← .

Install this way:

sudo wget -qO /usr/local/bin/nc-who https://global-social.net/script/nc-who
sudo chmod +x /usr/local/bin/nc-who
nc-who

Explanation:
- the first line downloads the script into the directory /usr/local/bin
- the second line makes it executable

You only need to install it once.
As all of my → ebtb ← scripts, it comes signed and does an integrity check on the first run and checks for updates on every startup.

Simply run:

nc-who monitor

or

nc-who last

much luck with it. :+1:


ernolf

4 Likes
  • Only mysql as database, pgsql is not yet supported by this script

What a pity 


@abyss02 try the newest version, I integrated PostgreSQL support for you.

2 Likes

Well done!

I kinda like to move this thread to “howto”-category. What do you think about it, @ernolf ?

Aww and is there any chance. making this an app for appstore with kind of like a html (or whatever)-output for admins?

anyway
 great work!

1 Like
  • :white_check_mark: done

Wooo, works great 


1 Like

Thank you for your kind feedback! I am happy that postgre - thanks to you - works now :wink:

I’ve increased the functionality of nc-who a bit again. Specialy the last_login function could be interesting for some admins but the realtime login status in monitor view as well.

Here the new help screen:

Help:

  nc-who - Version 2024-02-28 14:02 (latest version)

  This utility is similar to the Unix `who` command, allowing you to monitor
  live user logins and activities on your nextcloud server-instance.

  Usage:
    nc-who -h|--help
    nc-who monitor
    nc-who last
    nc-who integrity_check

  Options:

    -h|--help       Display this help message.

    monitor     Monitor live user logins, ordered by last activity at an
                adjustable refresh rate.
                * Login status is only available for cookie-based sessions
                  on a web frontend.
                * Last activity is shown for all clients.

    last        List users sorted by their last login time. This is equivalent
                to the output of `occ user:lastseen --all`
                * `--all` is actually not available for that occ command.

    integrity_check
                verify the integrity of this script with signature

Those of you who already have it installed (version 2023.06.29 or newer) only need to call the script and the update will be offered automatically.

Feedback welcome!

Continued luck

ernolf

Found a small bug in the current nc-who script.
If using nc dbpass with “$” sign, line 400 fails because “$” is used unescaped.

It must read:

eval '$DB_STRG' $DB_EXEC\"$db_query\"$

Thank you very much for your feedback!

Your Issue is verry good, I did realy not test it with passwords containing ‘$’

Could you please restart the script, it will ask to update and try if it now works.

ernolf

That was fast. It works now. Thanks.

1 Like

Unfortunately this breaks support for postgresql. I will have to develop a better solution. :wink:

Much luck,
ernolf

Now I hope it supports all kind of passwords for both, MySQL/MariaDB and PostgrSQL.

@atomic : does it still work?

ernolf

Hello @ernolf

Thanks for the link from this thread :arrow_down:

You doesn’t edit the bash script “minified”, right?
Is there a repository around with the code in a mode readable format?

What does it brings to “minify” a bash script? :thinking: is it obfuscation?

Thanks any way I’ll look at it. :+1:

Regards,
Sylvain.

Hi @Sylvain,

thank you for your interest,

I initially developed my scripts as monolithic standalone entities. However, given that many of the steps within most scripts remained consistent, I transitioned to modular scripting. This switch not only expedited development but also yielded significant enhancements applicable across my entire script collection.

Upon initiating the nc-who script, the necessary modules are loaded into the /usr/local/include/ernolf/prod/ directory. You’re welcome to explore the contents there.

Essentially, nc-who functions as a module loader with sequence control.

I am actually used to write my code “minified” this way because I can let it run better in my mind’s eye that way. I have consistently implemented this as an approach in the Module Loader, which I’ve optimized for compactness, ensuring minimal space consumption. The objective is to render it as “stable and solid as a rock,” given its foundational role in all of my scripts.
The loaded modules are more “human readable” formatted though :wink:

I host all my scripts on my personal server and have devised a custom build and commit framework. This framework handles all aspects of publication, including GPG signing, hashing, and versioning. I find platforms like Github or Codeberg too restrictive, as they lack the flexibility I require, I feel far too restricted in processes that I didn’t develop myself. :wink:
However, I’m happy to share the code if you specify the exact portion you’re interested in.

nc-who represents one of my simpler scripts. In addition to standard modules for color, text formatting, and interactive question/answer functionality etc., it relies on the “nextcloud” module for configuration data retrieval, the “nextcloud_db” module for interacting with the Nextcloud database, and the “nc-who/monitor” and “nc-who/last” modules, which execute the script’s tasks.


ernolf

Maybe this will help you:

nc-who monitor basically makes this database query that repeats itself at an adjustable time interval:

MySQL:

SELECT FROM_UNIXTIME(at.last_activity) AS last_activity,
                        CASE
                          WHEN at.type = '0' AND at.remember = '1' THEN (SELECT us.status FROM oc_user_status us WHERE us.user_id = at.uid)
                          ELSE 'n.a.'
                        END AS status, 
                        at.uid, at.name AS client
                      FROM oc_authtoken at WHERE at.type = '0' AND at.remember = '1'
                      ORDER BY at.last_activity DESC

PostgreSQL:

SELECT TO_TIMESTAMP(at.last_activity) AS last_activity,
                        CASE
                          WHEN at.type = '0' AND at.remember = '1' THEN (SELECT us.status FROM oc_user_status us WHERE us.user_id = at.uid)
                          ELSE 'n.a.'
                        END AS status, 
                        at.uid, at.name AS client
                      FROM oc_authtoken at WHERE at.type = '0' AND at.remember = '1'
                      ORDER BY at.last_activity DESC

All the rest of the code is to format it correctly on as many terminals as possible, including less wide TTYs, and to make it work out of the box on as many systems as possible.


Much and good luck,
ernolf

1 Like

Meanwhile there is:


ernolf

1 Like

Nextcloud All-in-One is now supported, containerized solutions other than AIO are not (yet) supported


ernolf

1 Like

Hola @ernolf !

Voy a escribir en castellano ( mi nativo ) por si fallo en la traducción, pero intentaré traducir al final.

Me gustĂł mucho el trabajo, y creo que puede ser muy Ăștil.
Soy administrador de sistemas y en un servidor que corro con NC, estaba interesado en verificar que los usuarios que permanecieran conectados, fueran los que correspondĂ­an.

Para probar el script tengo una måquina virtual en casa con NC y pude ver algo que no sé si es un error, mås bien un detalle que puede desconcertar la primera vez.

Si no hay ningĂșn usuario conectado, la pantalla no muestra nada, ni el cursor ya que estĂĄ oculto, lo que no deberĂ­a ser un resultado deseado. SerĂ­a mĂĄs informativo mostrar todo el encabezado del resultado y ningĂșn usuario listado o un mensaje informando que no hay usuarios conectados.
La primera vez que corrĂ­ el monitor por ejemplo, al no haber usuarios, la pantalla quedĂł en blanco ( en negro en realidad ), luego de una espera que considerĂ© razonable, intentĂ© dar por terminada la prueba y salĂ­ con Ctl+C , pensando que podĂ­a estar “colgado”. Entonces volviĂł a la terminal, pero el cursor continuĂł oculto, lo que es algo incĂłmodo.

AĂșn no he tenido tiempo de revisar todas las rutinas del directorio /usr/include/ebtb/prod/ , y aquĂ­ es donde el cĂłdigo “legible” y los comentarios nos permitirĂ­an ser de mĂĄs ayuda para poder modificar y probar, para ayudar en la soluciĂłn.

Bueno, por una entrada es demasiado.
Gracias por compartir tus conocimientos y tu trabajo !
@Ruben-cipo

Hi @ernolf !
I’m going to write in Spanish (my native) in case I fail in the translation, but I’ll try to translate in the end.
I really enjoyed the work, and I think it can be very useful.
I am a sysadmin and on a server that I run with NC, I was interested in verifying that the users who remained connected were the correct ones.
To test the script I have a virtual machine at home with NC and I could see something that I don’t know if it’s an error, but rather a detail that can be disconcerting the first time.
If there are no users logged in, the screen displays nothing, not even the cursor as it is hidden, which should not be a desired result. It would be more informative to show the entire result header and no users listed or a message informing that there are no users logged in.
For example, the first time I ran the monitor, when there were no logged in users, the screen went blank (actually black), after a wait that I considered reasonable, I tried to end the test and exited with Ctl+C , thinking that it might be “hanging”. Then it returned to the terminal, but the cursor remained hidden, which is somewhat inconvenient.
I haven’t had time to review all the routines in the /usr/include/ebtb/prod/ directory yet, and this is where “human readable” code, and comments would be of more help to us in modifying and testing, to aid in the solution.
Well, for one entry that’s too much.
Thank you for sharing your knowledge and your work!
@Ruben-cipo

1 Like

Hi @Ruben-cipo ,

thank you very much for your feedback,

Absolutely correct. The cursor is hidden there.
If you want to test the script, you should log in with some users. Without that, the script does not make any sense at all.

But, with all due respect, that is not the script’s job to say that nobody is logged in when nobody is logged in. That somehow follows automatically from the empty display.
If you call unix `who`, you aint get no negative messages either, only who is realy loged in at present


It sometimes needs a little time for all TRAPS to execute, in order to bring the cursor back. In some rare situations that does not work proper. I don’t know how you exactly testet it and what your terminal settings are.
However, it is better to abort with “q” as provided by the script.
Or was the first line (like this):

 coockie based logins, refresh rate = 5 s. - [s] change refresh rate - [r] reload - [b] back - [q] quit

not displayed either?

You can find the code on github. It is part of ebtb

I have described there, how you can build the code with your own local module server.
However, I haven’t tried it for a while now to see if it still works with the local server. If there are any problems, I’ll be happy to help or make the necessary adjustments to the code when I get the chance.

You are welcome to PM me for further details.


Buena suerte,
ernolf