diff --git a/login-log.py b/login-log.py index 4da5a39..3daed45 100644 --- a/login-log.py +++ b/login-log.py @@ -1,4 +1,5 @@ import os +import socket from datetime import date from datetime import datetime @@ -11,7 +12,7 @@ if os.name == 'nt': # For OS which are not MS Windows else: logfile = os.path.join(os.path.join(os.environ['HOME']), - r'Documents\login.log') + r'Documents/login.log') # Create the file if it does not exist yet if not os.path.exists(logfile): @@ -29,6 +30,11 @@ current_time = now.strftime("%H:%M:%S") # Determine the client hostname client_hostname = os.getenv("CLIENTNAME") +# Determine the client hostname via a different method +# in case the first one failed +if client_hostname is None: + client_hostname = socket.gethostbyaddr(socket.gethostname())[0] + # Class for prepending the information to the log file class Prepender(object): diff --git a/logoff-log.py b/logoff-log.py index 4a800a8..ddb2000 100644 --- a/logoff-log.py +++ b/logoff-log.py @@ -1,10 +1,18 @@ import os +import socket from datetime import date from datetime import datetime -# Set the location of the file to write to, in the user Documents directory -logfile = os.path.join(os.path.join(os.environ['USERPROFILE']), - r'Documents\logoff.log') + +# Determine if the OS is MS Windows +if os.name == 'nt': + # Set the location of the file to write to, in the user Documents directory + logfile = os.path.join(os.path.join(os.environ['USERPROFILE']), + r'Documents\logoff.log') +# For OS which are not MS Windows +else: + logfile = os.path.join(os.path.join(os.environ['HOME']), + r'Documents/logoff.log') # Create the file if it does not exist yet if not os.path.exists(logfile): @@ -16,10 +24,16 @@ today = date.today() now = datetime.now() current_day = today.strftime("%d.%m.%Y") -# print("Today's date:", current_day) current_time = now.strftime("%H:%M:%S") -# print("Current Time =", current_time) + +# Determine the client hostname +client_hostname = os.getenv("CLIENTNAME") + +# Determine the client hostname via a different method +# in case the first one failed +if client_hostname is None: + client_hostname = socket.gethostbyaddr(socket.gethostname())[0] # Class for prepending the date and time to the log file @@ -55,10 +69,10 @@ class Prepender(object): self.__open_file.close() -# Prepend the determined date and time to the top of the log file +# Prepend the determined information to the top of the log file with Prepender(logfile) as f: # Must write individual lines in reverse order - f.write_line(current_day+' - '+current_time) + f.write_line(current_day+' - '+current_time+' - '+client_hostname) # Or, use write_lines instead - that maintains order. # with Prepender(logfile) as f: