about summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorahriman <ahriman@falte.red>2019-12-18 09:55:03 -0500
committerahriman <ahriman@falte.red>2019-12-18 09:55:03 -0500
commitc9bf49c5c2ab0248301d96d73ab1618c08a11d07 (patch)
treee2b8ef2723778f04c4fe0643efe3e5846222867e
parentac0e7395e5a47457bc90e919234e931e33612bc4 (diff)
downloadadmin-c9bf49c5c2ab0248301d96d73ab1618c08a11d07.tar.gz
kneezle's newuseralertv3.py
-rw-r--r--.gitignore1
-rw-r--r--README.md7
-rwxr-xr-xbin/newuseralertv3.py157
3 files changed, 162 insertions, 3 deletions
diff --git a/.gitignore b/.gitignore
index 790d2f4..9de4f26 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,3 +3,4 @@ fuzzies.log
 users-added.log
 newusers.dat
 newuseralert.py
+gotifytokens.txt
diff --git a/README.md b/README.md
index d88ff5d..d96ccbc 100644
--- a/README.md
+++ b/README.md
@@ -9,10 +9,11 @@ The scripts are a mixture of both `Bash` and `Python`
 
 Everything was written by me, except for the following, which were *not* written by me:
   * `bin/showwhoison` (written by Kneezle, the co-administrator who joined the project in March 2019)
-  * `bin/newmail.sh` (same as above)
-  * `bin/newuseralert.py` (same as above)
+  * `bin/newmail.sh` (Kneezle)
+  * `bin/newuseralert.py` (Kneezle)
+  * `bin/newuseralertv3.py` (Kneezle)
   * `bin/toot.py` (written by Ben Harris of [tilde.team](https://tilde.team))
 
 `bin/makeuser` is originally based on [tilde.team](https://tilde.team)'s, but has been extended and modified so much it bears very little resemblance to the original.
 
-The source code for `instistats` is at [`github.com/gbmor/instistats`](https://github.com/gbmor/instistats).
+The source code for `instistats` (`tilde.json` generator) is at [`github.com/gbmor/instistats`](https://github.com/gbmor/instistats).
diff --git a/bin/newuseralertv3.py b/bin/newuseralertv3.py
new file mode 100755
index 0000000..b62a4bc
--- /dev/null
+++ b/bin/newuseralertv3.py
@@ -0,0 +1,157 @@
+#!/usr/local/bin/python3
+import os
+import argparse
+import http.client
+import sys
+import time
+
+aboutme = """
+# New User Monitor
+# Created for tilde.institute and Ahriman by Kneezle
+# BSD Rocks!
+
+# Version 3.0
+# This version supports hiding the gotify keys by passing them in via the CLI
+# or using the gotifynotify ENV variable to hide from a PS lookup
+"""
+
+defaulttitle = "Alert: New Users"
+
+defaultnewuserpath = "/admin/newusers.dat"
+
+runcmdtemplate = """curl -X POST "https://gotify.tildeverse.org/message?token={}" -F "title=Alert: New Users" -F "message={}" -F "priority=5" """
+
+ap = argparse.ArgumentParser()
+ap.add_argument('--newuserpath', default=defaultnewuserpath,
+                    help='sets the path for the new user txt file')
+
+ap.add_argument('--title', default=defaulttitle,
+                    help='sets the title')
+
+ap.add_argument('--usecurl', default=False,
+                    help='use curl or build in sockets')
+
+ap.add_argument("-a", "--about", dest='about', action='store_true', help="about me")
+
+ap.add_argument("--daemonize", dest='daemonize', action='store_true', help="run in a loop vs only run once")
+
+ap.add_argument('--gotifykeys', nargs='+', default=[],help="the gotify keys of the people to send to")
+
+ap.add_argument('--gotifykeypath', default=None,
+                    help='Load CSV gotify keys from file')
+
+ap.add_argument('--loopinterval', default=60,
+                    help='sets loop interval (seconds) in daemon mode')
+
+args = vars(ap.parse_args())
+
+if args['about']:
+    print(aboutme)
+    exit()
+
+
+title = args['title']
+newuserpath = args['newuserpath']
+usecurl = args['usecurl']
+gotifytokens = args['gotifykeys']
+daemonize = args['daemonize']
+gotifykeypath = args['gotifykeypath']
+loopinterval = int(args['loopinterval'])
+
+
+if gotifykeypath is not None:
+    with open(gotifykeypath) as f:
+        first_line = f.readline()
+        gotifytokens = first_line.rstrip("\n").split(',')
+
+
+if len(gotifytokens) < 1:
+    #we didn't get passed a token. lets try to get from ENV before giving up.
+    try:
+        envtokens = os.environ["gotifynotify"]
+    except KeyError:
+        print("You didn't provide a gotify token!")
+        sys.exit(1)
+    gotifytokens = envtokens.split(',')
+    if len(gotifytokens) < 1:
+        print("You didn't provide a gotify token!")
+        sys.exit(1)
+
+
+boilerplate = """New pending user found!
+
+Username: {}
+Email: {}
+
+"""
+
+#we have no do while in python so this will have to do
+firstloop = True
+
+previouslinecount = 0
+
+while firstloop or daemonize:
+    if not firstloop:
+        time.sleep(loopinterval) #so we don't hammer the CPU in daemon mode
+
+    with open(newuserpath) as fp:
+        line = fp.readline()
+        linecount = 1
+        numnonblanklines = 0
+        push_notification = ""
+        while line:
+            if line.strip() != "": #not a blank line
+                numnonblanklines = numnonblanklines + 1
+                print("New User Found: {} : {}".format(linecount, line.strip()))
+
+                #lets extract the useful information
+                x = line.split(" ")
+                sshkey = ""
+                itemno = 0
+                for item in x:
+                    if itemno > 1:
+                        sshkey = sshkey + " " + item
+                    itemno = itemno + 1
+                sshkey = sshkey.replace('"', "")
+
+                #Lets build the single push notification with all the details
+
+                push_notification = push_notification + boilerplate.format(x[0], x[1])
+            linecount = linecount + 1
+            line = fp.readline()
+
+    #notify is when handled
+    if previouslinecount > numnonblanklines:
+        for key in gotifytokens:
+            if not usecurl:
+                conn = http.client.HTTPSConnection("gotify.tildeverse.org")
+                payload = """title={}&message={}&priority=5""".format("New users handled", "Someone on the admin team got it.")
+                headers = {'content-type': "application/x-www-form-urlencoded"}
+                conn.request("POST", "/message?token={}".format(key), payload, headers)
+                res = conn.getresponse()
+                data = res.read()
+                print(data.decode("utf-8"))
+            else:
+                torun = runcmdtemplate.format(key, push_notification)
+                os.system(torun)
+
+    if numnonblanklines > 0 and numnonblanklines > previouslinecount:
+        if numnonblanklines > 4:
+            push_notification = "You have " + str(numnonblanklines) + " pending new users!"
+        for key in gotifytokens:
+            if not usecurl:
+                conn = http.client.HTTPSConnection("gotify.tildeverse.org")
+                payload = """title={}&message={}&priority=5""".format(title, push_notification)
+                headers = {'content-type': "application/x-www-form-urlencoded"}
+                conn.request("POST", "/message?token={}".format(key), payload, headers)
+                res = conn.getresponse()
+                data = res.read()
+                print(data.decode("utf-8"))
+            else:
+                torun = runcmdtemplate.format(key, push_notification)
+                os.system(torun)
+    else:
+        print("No new users pending")
+    previouslinecount = numnonblanklines
+    firstloop = False #no longer the first loop
+    print("prev: " + str(previouslinecount))