-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathChecker.cs
362 lines (316 loc) · 16.4 KB
/
Checker.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
using check_up_money.Cypher;
using FreeSpaceChecker.Interfaces;
using FreeSpaceChecker.Settings;
using Org.BouncyCastle.Ocsp;
using Org.BouncyCastle.Utilities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
namespace FreeSpaceChecker
{
class Checker
{
private string loggerPath;
Configurator conf;
private ILogger logger;
ICypher encryptor;
private IMailSender sender;
private ISpaceChecker checker;
private List<Comp> comps;
private (bool sendEmail, string smtpServer, string mailFrom,
string mailLogin, string mailLoginSalt, string mailPassword, string mailPasswordSalt) smtpSettings;
private List<Mail> mails;
RequisiteInformation requisiteInformation;
RequisiteInformation mailReqs;
private enum DiskSizeFormatType
{
Bytes = 0,
KiloBytes = 1,
MegaBytes = 2,
GigaBytes = 3,
TeraBytes = 4
}
public Checker()
{
conf = new Configurator();
loggerPath = Path.Combine(conf.GetLoggerPath(), "FreeSpaceChecker" + "_" + DateTime.Now.Year.ToString() + ".txt");
var req = conf.LoadAdminSettings();
encryptor = new Encryptor();
CheckRequisites(req, conf);
logger = new Logger(loggerPath);
sender = new MailSender(logger, encryptor);
checker = new FreeSpaceChecker();
comps = conf.LoadCompSettings();
smtpSettings = conf.LoadSmtpSettings();
mails = conf.LoadMailSettings();
PerfomCheck(smtpSettings.sendEmail);
}
private void CheckRequisites((string admLogin, string loginSalt, string admPass, string passSalt) req, Configurator conf)
{
if(string.IsNullOrEmpty(req.admLogin) || string.IsNullOrEmpty(req.admPass))
{
Console.WriteLine("Не задан пароль или логин. Введите логин и пароль через пробел: ");
while (true)
{
var loginAdnPass = (Console.ReadLine().Split());
if(loginAdnPass.Length != 2 || string.IsNullOrEmpty(loginAdnPass[0]) || string.IsNullOrEmpty(loginAdnPass[1]))
{
Console.WriteLine("Ошибка ввода. Введите логин и пароль через пробел: ");
continue;
}
else
{
(string admLogin, string admPass) newReq = (loginAdnPass[0], loginAdnPass[1]);
var enc = encryptor.Encrypt(encryptor.ToSecureString(loginAdnPass[0]), encryptor.ToSecureString(loginAdnPass[1]));
requisiteInformation = enc;
newReq.admLogin = encryptor.ToInsecureString(enc.User);
newReq.admPass = encryptor.ToInsecureString(enc.Password);
Console.WriteLine("Enc: " + newReq.admLogin + " " + newReq.admPass);
conf.SaveAdminSettings((encryptor.ToInsecureString(enc.User), enc.USalt,
encryptor.ToInsecureString(enc.Password), enc.PSalt));
}
if (Console.ReadKey().Key == ConsoleKey.Enter)
break;
}
}
else
{
Console.WriteLine("Login and password - OK");
requisiteInformation =
new RequisiteInformation(encryptor.ToSecureString(req.admLogin), req.loginSalt, encryptor.ToSecureString(req.admPass), req.passSalt);
}
}
private RequisiteInformation CheckMailRequisites((string mailLogin, string mailLoginSalt, string mailPassword, string mailPasswordSalt) req, Configurator conf)
{
if (string.IsNullOrEmpty(req.mailLogin) || string.IsNullOrEmpty(req.mailPassword))
{
Console.WriteLine("Не задан пароль или логин для почты. Введите логин и пароль через пробел: ");
while (true)
{
var loginAdnPass = (Console.ReadLine().Split());
if (loginAdnPass.Length != 2 || string.IsNullOrEmpty(loginAdnPass[0]) || string.IsNullOrEmpty(loginAdnPass[1]))
{
Console.WriteLine("Ошибка ввода. Введите логин и пароль для почты через пробел: ");
continue;
}
else
{
(string mailLogin, string mailPassword) newReq = (loginAdnPass[0], loginAdnPass[1]);
var enc = encryptor.Encrypt(encryptor.ToSecureString(loginAdnPass[0]), encryptor.ToSecureString(loginAdnPass[1]));
mailReqs = enc;
newReq.mailLogin = encryptor.ToInsecureString(enc.User);
newReq.mailPassword = encryptor.ToInsecureString(enc.Password);
Console.WriteLine("Enc: " + newReq.mailLogin + " " + newReq.mailPassword);
conf.SaveSmtpReqSettings(encryptor.ToInsecureString(enc.User), enc.USalt,
encryptor.ToInsecureString(enc.Password), enc.PSalt);
}
if (Console.ReadKey().Key == ConsoleKey.Enter)
break;
}
}
else
{
Console.WriteLine("Login and password for mail - OK");
mailReqs =
new RequisiteInformation(encryptor.ToSecureString(req.mailLogin), req.mailLoginSalt,
encryptor.ToSecureString(req.mailPassword), req.mailPasswordSalt);
}
return mailReqs;
}
/// <summary>
/// Запуск проверки
/// </summary>
public void PerfomCheck(bool sendMail = true)
{
int lowSpaceAndAvailabilityCounter = 0;
ServerAvailabilityChecker sac = new ServerAvailabilityChecker();
logger.Log("Perfoming daily checking.");
List<Tuple<bool, string, string, string, string, string>> msgBlob =
new List<Tuple<bool, string, string, string, string, string>>();
foreach(Comp comp in comps)
{
bool serverAvailability = sac.CheckServer(comp.Ip, logger);
// Check server availability
if (serverAvailability)
{
foreach (Tuple<string, ulong> diskAndTreshold in GetDiskAndTreshold(comp.Disks))
{
string drive = diskAndTreshold.Item1;
Tuple<ulong, ulong> freeAndTotalSpace = checker.CheckSpace(comp.Ip,
drive, logger, requisiteInformation, encryptor, drive.Contains("=") ? true : false);
ulong treshold = diskAndTreshold.Item2;
string formTreshold = FormatSizeBytes(treshold);
ulong space = freeAndTotalSpace.Item1;
double freeSpace = Math.Round((double)freeAndTotalSpace.Item1 * 100 / (double)freeAndTotalSpace.Item2, 2);
string freeSpaceProcentage = freeSpace.ToString() + "%";
string size = FormatSizeBytes(space);
if (freeSpace == 0.0)
{
logger.Log("Server: " + comp.Ip.PadRight(15)
+ " " + drive.PadRight(15) + ": " + size.PadRight(10)
+ " Free %: " + freeSpaceProcentage.PadLeft(6)
+ " Treshold: " + formTreshold.PadLeft(8)
+ " << Server unavailable!");
msgBlob.Add(new Tuple<bool, string, string, string, string, string>(serverAvailability,
comp.Ip, drive, "NO RESPONSE", "NO RESPONSE", formTreshold));
}
else if (treshold > space)
{
logger.Log("Server: " + comp.Ip.PadRight(15)
+ " " + drive.PadRight(15) + ": " + size.PadRight(10)
+ " Free %: " + freeSpaceProcentage.PadLeft(6)
+ " Treshold: " + formTreshold.PadLeft(8)
+ " << Low space!");
msgBlob.Add(new Tuple<bool, string, string, string, string, string>(serverAvailability,
comp.Ip, drive, size, freeSpaceProcentage, formTreshold));
lowSpaceAndAvailabilityCounter++;
}
else
{
logger.Log("Server: " + comp.Ip.PadRight(15)
+ " " + drive.PadRight(15)
+ ": " + size.PadRight(10)
+ " Free %: " + freeSpaceProcentage.PadLeft(6)
+ " Treshold: " + formTreshold.PadLeft(8));
}
}
}
else
{
// Server offline
logger.Log("Server: " + comp.Ip.PadRight(10)
+ " " + "NONE".PadRight(15) + ": " + "NONE".PadRight(10)
+ " Free %: " + "NONE".PadLeft(6)
+ " Treshold: " + "NONE".PadRight(9)
+ " << OFFLINE!");
msgBlob.Add(new Tuple<bool, string, string, string, string, string>(
serverAvailability, comp.Ip, "OFFLINE", "OFFLINE", "OFFLINE", "OFFLINE"));
lowSpaceAndAvailabilityCounter++;
}
}
logger.Log(string.Empty, true);
if(sendMail && lowSpaceAndAvailabilityCounter != 0)
{
CheckMailRequisites((smtpSettings.mailLogin, smtpSettings.mailLoginSalt, smtpSettings.mailPassword, smtpSettings.mailPasswordSalt), conf);
foreach (Mail mail in mails)
{
sender.SendEmail(MailComposer(msgBlob), mail.Subject, mail.Email, smtpSettings.smtpServer, smtpSettings.mailFrom,
encryptor.ToInsecureString(mailReqs.User),
mailReqs.USalt,
encryptor.ToInsecureString(mailReqs.Password),
mailReqs.PSalt);
}
}
Console.WriteLine("Check completed.");
Console.ReadLine();
}
/// <summary>
/// Компоновщик. Создает xml-шаблон с таблицей. Create xml-template for table.
/// </summary>
/// <param name="msgData">Подготовленные данные. Data: Ip - disk - size - free size in % - treshold</param>
/// <returns></returns>
private string MailComposer(List<Tuple<bool, string, string, string, string, string>> msgData)
{
StringBuilder result = new StringBuilder();
result.Append("<head><style>table, td, th { border: 1px solid black; width: 480px; }</style></head>");
result.Append("<h1>Attention! Low space on:</h1>");
result.Append("<table><tr><th>Server</th><th>Disk</th><th>Free space</th><th>Free %</th><th>Treshold</th></tr>");
foreach(Tuple<bool, string, string, string, string, string> data in msgData)
{
if (data.Item1)
{
result.Append(
"<tr><td style='text-align:center'>" + data.Item2
+ "</td><td style='text-align:center'>" + data.Item3 + ":"
+ "</td><td style='text-align:right'>" + data.Item4
+ "</td><td style='text-align:right'>" + data.Item5
+ "</td><td style='text-align:center'>" + data.Item6
+ "</td></tr>");
}
else
{
result.Append(
"<tr><td bgcolor='#FF0000' style='text-align:center'>" + data.Item2
+ "</td><td style='text-align:center'>" + data.Item3
+ "</td><td style='text-align:center'>" + data.Item4
+ "</td><td style='text-align:center'>" + data.Item5
+ "</td><td style='text-align:center'>" + data.Item6
+ "</td></tr>");
}
}
result.Append("</table>");
//result.Append("<h2><a href=" + "file:///" + @"\\G600-SRWORK\FreeSpaceChecker\logs\" + System.IO.Path.GetFileName(loggerPath) + ">Log file link</a></h2>");
//result.Append("<h3><a href=" + "file:///" + @"\\G600-SRWORK\FreeSpaceChecker\FreeSpaceChecker.exe.config" + ">Edit settings</a></h3>");
result.Append("<h2><a href=" + "file:///" + loggerPath + ">Log file link</a></h2>");
//result.Append("<h3><a href=" + "file:///" + Path.Combine(Path.GetFullPath(loggerPath), "FreeSpaceChecker.exe.config") + ">Edit settings</a></h3>");
return result.ToString();
}
/// <summary>
/// Получаем disk и treshold со строки настроек. Recieve disk and treshold from setting string.
/// </summary>
/// <param name="confData">Строка с настроек. Settings string</param>
/// <returns>Набор диск - лимит. Disk - treshold (bytes)</returns>
private List<Tuple<string, ulong>> GetDiskAndTreshold(string confData)
{
List<Tuple<string, ulong>> result = new List<Tuple<string,ulong>>();
ulong GBtoBytes = 1024L * 1024L * 1024L;
// If shares
if(!confData.Contains("="))
{
foreach (string dataGroup in confData.Split(','))
{
Match match = new Regex(@"(?<disk>\b[A-Za-z]\b)-(?<treshold>[0-9]+)").Match(dataGroup);
result.Add(new Tuple<string, ulong>(match.Groups["disk"].Value, ulong.Parse(match.Groups["treshold"].Value) * GBtoBytes));
}
}
else
{
Console.WriteLine("SHARES " + confData);
foreach(string dataGroup in confData.Split(','))
{
Match match = new Regex(@"(?<diskWithShare>(?<disk>\b[A-Za-z]\b)=(?<share>(\\[A-Za-z]+)+))-(?<treshold>\d+)").Match(dataGroup);
result.Add(new Tuple<string, ulong>(match.Groups["diskWithShare"].Value, ulong.Parse(match.Groups["treshold"].Value) * GBtoBytes));
}
}
return result;
}
/// <summary>
/// Format raw bytes to Kb, Mb, Gb, Tb
/// </summary>
/// <param name="dlBytes">Raw bytes</param>
/// <returns>Formatted string</returns>
private string FormatSizeBytes(ulong dlBytes)
{
if (dlBytes < 1048576)
{
return FormatSize(dlBytes, DiskSizeFormatType.KiloBytes).ToString("F").PadRight(6) + " Kb";
}
else if (dlBytes >= 1048576 && dlBytes < 1073741824)
{
return FormatSize(dlBytes, DiskSizeFormatType.MegaBytes).ToString("F").PadRight(6) + " Mb";
}
else if (dlBytes >= 1073741824 && dlBytes < 1099511627776)
{
return FormatSize(dlBytes, DiskSizeFormatType.GigaBytes).ToString("F").PadRight(6) + " Gb";
}
else
{
return FormatSize(dlBytes, DiskSizeFormatType.TeraBytes).ToString("F").PadRight(6) + " Tb";
}
}
/// <summary>
/// Get size for specific type
/// </summary>
/// <param name="freeBytes">Raw bytes</param>
/// <param name="type">Format type</param>
/// <returns>Formatted bytes</returns>
private decimal FormatSize(ulong freeBytes, DiskSizeFormatType type)
{
decimal formatedSizeFree;
formatedSizeFree = (decimal)(freeBytes / Math.Pow(1024, (int)type));
return formatedSizeFree;
}
}
}