0

I am looking for a way I can monitor if users are logged into certain computers in a network using Python and return the data to a single computer. Ideally I would like to be able to check each computer by ip address and see if a user is logged in or not. The computers have Windows.

so I want to build a function like this:

IP_ADDRESS = '123.123.123.123'
check_user(IP_ADDRESS)

output: users logged in: Ed

or

output: users logged in: N/A

2 Answers2

0

You must prepare MS Windows Service like this: How do you run a Python script as a service in Windows? Your service must open port for checking, you can use FastAPI. And you can check current user by: https://docs.python.org/3/library/getpass.html#getpass.getuser

user3804427
  • 432
  • 2
  • 12
  • Could I return this info to one single computer? I forgot to mention in the post the goal is to monitor this info from 1 master computer – CaptainEddy Oct 15 '20 at 12:03
  • Yes, you can run service with open network port. You software on master computer must check this ports – user3804427 Oct 15 '20 at 13:00
  • Understood. I will try it. Thank you!! – CaptainEddy Oct 15 '20 at 13:11
  • Did you try it? What result? – user3804427 Dec 22 '20 at 13:01
  • Hello, forgot to reply to you. yes I found a guy online that made some code which used python threading library to have a server interact with multiple clients. its a beautiful solution. works nicely when I package it into exe's. I adapted the code slightly to lock computers by number on command. I am not currently hosting this solution as a service on my network because I was not able to find a way to UNLOCK the computers. this makes it not very user friendly as it forces users to type in passwords. As far as I can tell.. it is not possible to use python to unclock computers. – CaptainEddy Jan 17 '21 at 23:42
0

The Following solution works nicely.

If someone knows a way to UNLCOK computers using python commands please let me know. I got this code off a guy online and adapted it for my purposes.

If anyone recognizes let me know so we can give credit. I can't remember his name.

This Is My Server

import socket
import argparse
import threading 
import csv



parser = argparse.ArgumentParser(description = "This is the server for the multithreaded socket demo!")
parser.add_argument('--host', metavar = 'host', type = str, nargs = '?', default = socket.gethostname())
parser.add_argument('--port', metavar = 'port', type = int, nargs = '?', default = 9999)
args = parser.parse_args()

print(f"Running the server on: {args.host} and port: {args.port}")

sck = socket.socket()
sck.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

try: 
    sck.bind((args.host, args.port))
    sck.listen(5)
except Exception as e:
    raise SystemExit(f"We could not bind the server on host: {args.host} to port: {args.port}, because: {e}")


def on_new_client(client, connection):
    ip = connection[0]
    port = connection[1]
    print(f"THe new connection was made from IP: {ip}, and port: {port}!")
    while True:
        msg = client.recv(1024)

        # with open('aa.csv', 'w', newline='') as csvfile:
        #     thewriter = csv.writer(csvfile)
        #     thewriter.writerow([msg.decode(),'computer 2'])

        if msg.decode() == 'exit':
            break
            
        if msg.decode() == 'lock computer 1':
            reply = 'lock'
            client.sendall(reply.encode('utf-8'))

        elif msg.decode() == 'open computer 1':
            reply = 'open'
            client.sendall(reply.encode('utf-8'))

        # print(f"The client said: {msg.decode()}")
        # reply = f"You told me: {msg.decode()}"


        # client.sendall(reply.encode('utf-8'))
    #print(f"The client from ip: {ip}, and port: {port}, has gracefully diconnected!")
    #client.close()

while True:
    try: 
        client, ip = sck.accept()
        threading._start_new_thread(on_new_client,(client, ip))
    except KeyboardInterrupt:
        print(f"Gracefully shutting down the server!")
    except Exception as e:
        print(f"Well I did not anticipate this: {e}")

sck.close()

This is My Client

import socket 
import argparse
import subprocess
import time
import subprocess

parser = argparse.ArgumentParser(description = "This is the client for the multi threaded socket server!")
parser.add_argument('--host', metavar = 'host', type = str, nargs = '?', default = socket.gethostname())
parser.add_argument('--port', metavar = 'port', type = int, nargs = '?', default = 9999)
args = parser.parse_args()

print(f"Connecting to server: {args.host} on port: {args.port}")

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sck:
    try:
        sck.connect((args.host, args.port))
    except Exception as e:
        raise SystemExit(f"We have failed to connect to host: {args.host} on port: {args.port}, because: {e}")

    while True:
        # msg = input("What do we want to send to the server?: ")

        time.sleep(2)
        # process_name='LogonUI.exe'
        # callall='TASKLIST'
        # outputall=subprocess.check_output(callall)
        # outputstringall=str(outputall)
        # if process_name in outputstringall:
        #     msg = 'Free'
        # else:
        #     msg = 'occupied'
        msg = ('lock computer 1')
        sck.sendall(msg.encode('utf-8'))

        if msg =='exit':
            print("Client is saying goodbye!")
            break

        data = sck.recv(1024)
        if data.decode() == 'lock':
            print('should I lock the computer?')
            process_name='LogonUI.exe'
            callall='TASKLIST'
            outputall=subprocess.check_output(callall)
            outputstringall=str(outputall)
            if process_name in outputstringall:
                print("Already locked")
            else: 
                print("needs to be locked.")

        print(f"The server's response was: {data.decode()}")