55import pysnmp .hlapi as snmp
66import re
77import yaml
8+ import socket
89
910# Assuming the YAML file is in the same directory as the script
1011script_dir = os .path .dirname (os .path .realpath (__file__ ))
4546os .makedirs (year_output_dir , exist_ok = True )
4647
4748
48- # Define the filename with the requested naming scheme
49+ # Define filenames
4950filename = f"totals_{ base_date :%Y_%m} .csv"
5051csvfile_path = os .path .join (year_output_dir , filename )
51- logfile = os .path .join (year_output_dir , "TodaysLog_PrinterCounter.txt" )
52+ todaysLog = os .path .join (year_output_dir , "TodaysLog_PrinterCounter.txt" )
5253
5354# Clear the log file at the start of each run
54- with open (logfile , "w" ):
55+ with open (todaysLog , "w" ):
5556 pass
5657
58+ # Define a reusable logging function
59+ def logMessage (logfile , message ):
60+ with open (logfile , 'a' ) as log :
61+ log .write (message + "\n " )
62+
63+ # Log the start of the script
64+
65+ start_time = datetime .now ().strftime ("%I:%M %p - %d %B %Y" )
66+ logMessage (todaysLog , f"***** { start_time } - starting script\n " )
67+ logMessage (todaysLog , socket .gethostname ())
68+
5769def sanitize_output (input_str ):
5870 truncated = input_str [:64 ]
5971 sanitized = '' .join (e for e in truncated if e .isalnum () or e .isspace ())
@@ -88,13 +100,15 @@ def get_printer_counts(ip, model):
88100
89101 bw_oids = get_matching_oids (OIDS_bw_known , OIDS_bw , model , default_oid )
90102 bw_count = try_snmp_get (ip , bw_oids )
91- print (f" { ip } bw_count: { bw_count } " )
103+ print (f" bw: { bw_count } " )
104+
105+ #logMessage(todaysLog, f" bw: {count_bw}")
92106
93107 color_count = ""
94108 if is_color :
95109 color_oids = get_matching_oids (OIDS_color_known , OIDS_color , model , default_oid )
96110 color_count = try_snmp_get (ip , color_oids )
97- print (f" { ip } color_count : { color_count } " )
111+ print (f" color : { color_count } " )
98112
99113 return bw_count if bw_count is not None else "" , color_count if color_count is not None else ""
100114
@@ -113,11 +127,8 @@ def get_matching_oids(known_oid_dict, oid_dict, model, default):
113127 for keys in oid_dict :
114128 # Split keys by comma and iterate over each possible match
115129 for key in keys .split (',' ):
116- # Normalize the key string by converting to lowercase and removing spaces
117130 normalized_key = key .strip ().lower ().replace (" " , "" )
118-
119131 if normalized_key in normalized_model :
120- # Return the list of OIDs, excluding any "null" entries
121132 return [oid for oid in oid_dict [keys ] if oid != "null" ]
122133
123134 # If no match is found, return the default OID
@@ -132,7 +143,7 @@ def try_snmp_get(ip, oids):
132143 return response
133144 return None
134145
135- # Get the current year and month
146+
136147current_year = datetime .now ().year
137148current_month = datetime .now ().month
138149
@@ -142,7 +153,6 @@ def try_snmp_get(ip, oids):
142153echo = f"searching: { foundprinters_dir } "
143154expected_file_path = os .path .join (year_output_dir , foundPrintersCSV )
144155
145- # Initialize printer_ips
146156printer_ips = []
147157
148158# Check if the expected file exists
@@ -164,7 +174,7 @@ def try_snmp_get(ip, oids):
164174 exit (1 )
165175
166176
167- # known OIDs fr bw and color
177+ # known OIDs fr bw and color. move to module someday.
168178OIDS_bw_known = {
169179 "KONICA MINOLTA bizhub C368" : ["1.3.6.1.4.1.18334.1.1.1.5.7.2.2.1.5.1.2" ],
170180 "ECOSYS M3860idn" : ["iso.3.6.1.4.1.1347.42.3.1.1.1.1.1" ],
@@ -225,7 +235,12 @@ def try_snmp_get(ip, oids):
225235 # Ping the IP address
226236 response = subprocess .run (['ping' , '-c' , '1' , '-W' , '1' , ip ], stdout = subprocess .PIPE , stderr = subprocess .PIPE )
227237 if response .returncode != 0 :
228- print (f"pinging { ip } - No response..." )
238+
239+
240+ response = f"pinging {{ip}} - No response..."
241+ print (response )
242+ logMessage (todaysLog , response )
243+
229244 serials_row += ","
230245 counts_row += ",,"
231246 model_row += ","
@@ -235,22 +250,28 @@ def try_snmp_get(ip, oids):
235250
236251 # Get printer model
237252 model = get_printer_model (ip )
238- print (f">>>>>>>: { ip } : { model } " )
253+ response2 = f" model: { model } "
254+ print (response2 )
255+ logMessage (todaysLog , response2 )
239256 model_row += f",{ model } ,"
240257
241258 # Query serial number
242- print (f" { ip } Serial: " , end = '' )
259+ print (f" Serial: " , end = '' )
243260 serial = try_snmp_get (ip , oid_serial )
244261 serial = sanitize_output (serial ) if serial is not None else ""
245262 print (serial )
246263 serials_row += f",{ serial } , <--"
247264
248265 # Get printer counts
249266 count_bw , count_color = get_printer_counts (ip , model )
267+ logMessage (todaysLog , f" bw: { count_bw } " )
268+ logMessage (todaysLog , f" Col: { count_color } " )
269+ logMessage (todaysLog , f" serial: { serial } " )
250270
251271 # Append counts to counts row
252272 counts_row += f",{ count_bw } ,{ count_color } "
253273
274+
254275# Check if the file already exists
255276if os .path .exists (csvfile_path ):
256277 print ("Appending totals to CSV..." )
@@ -267,10 +288,15 @@ def try_snmp_get(ip, oids):
267288 writer .writerow (type_row .split (',' ))
268289 writer .writerow (counts_row .split (',' ))
269290
270- print (f"Totals appended to or written to { filename } " )
291+ print (f"Totals written to: { filename } " )
292+ logMessage (todaysLog , f"Totals written to: { filename } " )
271293
272294# Get the end time
273295timeend = datetime .now ()
296+ #time began
297+ logMessage (todaysLog , f" started: { timestart } " )
298+ logMessage (todaysLog , f" finished: { timeend } " )
274299elapsed_time = timeend - timestart
275300formatted_elapsed_time = format_elapsed_time (elapsed_time , format_type = 1 )
276- print (f"All done in { elapsed_time } seconds" )
301+ print (f"All done in { elapsed_time } " )
302+ logMessage (todaysLog , f" total time: { elapsed_time } " )
0 commit comments