5
5
import pysnmp .hlapi as snmp
6
6
import re
7
7
import yaml
8
+ import socket
8
9
9
10
# Assuming the YAML file is in the same directory as the script
10
11
script_dir = os .path .dirname (os .path .realpath (__file__ ))
45
46
os .makedirs (year_output_dir , exist_ok = True )
46
47
47
48
48
- # Define the filename with the requested naming scheme
49
+ # Define filenames
49
50
filename = f"totals_{ base_date :%Y_%m} .csv"
50
51
csvfile_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" )
52
53
53
54
# Clear the log file at the start of each run
54
- with open (logfile , "w" ):
55
+ with open (todaysLog , "w" ):
55
56
pass
56
57
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
+
57
69
def sanitize_output (input_str ):
58
70
truncated = input_str [:64 ]
59
71
sanitized = '' .join (e for e in truncated if e .isalnum () or e .isspace ())
@@ -88,13 +100,15 @@ def get_printer_counts(ip, model):
88
100
89
101
bw_oids = get_matching_oids (OIDS_bw_known , OIDS_bw , model , default_oid )
90
102
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}")
92
106
93
107
color_count = ""
94
108
if is_color :
95
109
color_oids = get_matching_oids (OIDS_color_known , OIDS_color , model , default_oid )
96
110
color_count = try_snmp_get (ip , color_oids )
97
- print (f" { ip } color_count : { color_count } " )
111
+ print (f" color : { color_count } " )
98
112
99
113
return bw_count if bw_count is not None else "" , color_count if color_count is not None else ""
100
114
@@ -113,11 +127,8 @@ def get_matching_oids(known_oid_dict, oid_dict, model, default):
113
127
for keys in oid_dict :
114
128
# Split keys by comma and iterate over each possible match
115
129
for key in keys .split (',' ):
116
- # Normalize the key string by converting to lowercase and removing spaces
117
130
normalized_key = key .strip ().lower ().replace (" " , "" )
118
-
119
131
if normalized_key in normalized_model :
120
- # Return the list of OIDs, excluding any "null" entries
121
132
return [oid for oid in oid_dict [keys ] if oid != "null" ]
122
133
123
134
# If no match is found, return the default OID
@@ -132,7 +143,7 @@ def try_snmp_get(ip, oids):
132
143
return response
133
144
return None
134
145
135
- # Get the current year and month
146
+
136
147
current_year = datetime .now ().year
137
148
current_month = datetime .now ().month
138
149
@@ -142,7 +153,6 @@ def try_snmp_get(ip, oids):
142
153
echo = f"searching: { foundprinters_dir } "
143
154
expected_file_path = os .path .join (year_output_dir , foundPrintersCSV )
144
155
145
- # Initialize printer_ips
146
156
printer_ips = []
147
157
148
158
# Check if the expected file exists
@@ -164,7 +174,7 @@ def try_snmp_get(ip, oids):
164
174
exit (1 )
165
175
166
176
167
- # known OIDs fr bw and color
177
+ # known OIDs fr bw and color. move to module someday.
168
178
OIDS_bw_known = {
169
179
"KONICA MINOLTA bizhub C368" : ["1.3.6.1.4.1.18334.1.1.1.5.7.2.2.1.5.1.2" ],
170
180
"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):
225
235
# Ping the IP address
226
236
response = subprocess .run (['ping' , '-c' , '1' , '-W' , '1' , ip ], stdout = subprocess .PIPE , stderr = subprocess .PIPE )
227
237
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
+
229
244
serials_row += ","
230
245
counts_row += ",,"
231
246
model_row += ","
@@ -235,22 +250,28 @@ def try_snmp_get(ip, oids):
235
250
236
251
# Get printer model
237
252
model = get_printer_model (ip )
238
- print (f">>>>>>>: { ip } : { model } " )
253
+ response2 = f" model: { model } "
254
+ print (response2 )
255
+ logMessage (todaysLog , response2 )
239
256
model_row += f",{ model } ,"
240
257
241
258
# Query serial number
242
- print (f" { ip } Serial: " , end = '' )
259
+ print (f" Serial: " , end = '' )
243
260
serial = try_snmp_get (ip , oid_serial )
244
261
serial = sanitize_output (serial ) if serial is not None else ""
245
262
print (serial )
246
263
serials_row += f",{ serial } , <--"
247
264
248
265
# Get printer counts
249
266
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 } " )
250
270
251
271
# Append counts to counts row
252
272
counts_row += f",{ count_bw } ,{ count_color } "
253
273
274
+
254
275
# Check if the file already exists
255
276
if os .path .exists (csvfile_path ):
256
277
print ("Appending totals to CSV..." )
@@ -267,10 +288,15 @@ def try_snmp_get(ip, oids):
267
288
writer .writerow (type_row .split (',' ))
268
289
writer .writerow (counts_row .split (',' ))
269
290
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 } " )
271
293
272
294
# Get the end time
273
295
timeend = datetime .now ()
296
+ #time began
297
+ logMessage (todaysLog , f" started: { timestart } " )
298
+ logMessage (todaysLog , f" finished: { timeend } " )
274
299
elapsed_time = timeend - timestart
275
300
formatted_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