public void SendClientJob(InquiryEntity ie) { var xmlSerializer = new XmlSerializer(typeof(InquiryEntity)); if (Stream.CanWrite) { byte[] msg = Encoding.UTF8.GetBytes("sendingjob\r\n"); try { Stream.Write(msg, 0, msg.Length); } catch (Exception e) { PrintConsoleMessage(MessageType.ERROR, "ОШИБКА отправки подготовки к отправке задания клиенту", e.Message, e.StackTrace); } try { StringWriter tw = new StringWriter(); xmlSerializer.Serialize(tw, ie); byte[] msg1 = Encoding.UTF8.GetBytes(tw.ToString() + "\r\nfff\r\n"); Stream.Write(msg1, 0, msg1.Length); } catch (Exception e) { PrintConsoleMessage(MessageType.ERROR, $"ОШИБКА отправки клиенту задания клиенту {Client.Client.RemoteEndPoint}", e.Message, e.StackTrace); } } }
private InquiryEntity ParseCommand() { InquiryEntity result = new InquiryEntity(); try { //todo сделать нормально using (StreamReader sr = new StreamReader(new NetworkStream(client.Client))) { string a = sr.ReadLine(); string[] b = a.Split(','); TaskEntity t = new TaskEntity { Name = b[0], Path = b[1], //todo fail with "C:\Program Files (x86)\" path Type = b[2] }; List <TaskEntity> l = new List <TaskEntity>(); l.Add(t); result.Method = "wmi"; result.Tasks = l; } } catch (Exception e) { PrintConsoleMessage(MessageType.ERROR, "ОШИБКА обработки задания", e.Message, e.StackTrace); } return(result); }
public void SendBroadcastJob(InquiryEntity ie) { foreach (var client in Clients) { client.Value.SendClientJob(ie); } }
private static void CompareFiles(InquiryEntity ie) { if (string.IsNullOrEmpty(ie.File1)) { Console.WriteLine(@"Не указан файл №1. Укажите его через опцию ""/1"""); return; } if (string.IsNullOrEmpty(ie.File2)) { Console.WriteLine(@"Не указан файл №2. Укажите его через опцию ""/2"""); return; } Comparsion.Compare(ie.File1, ie.File2); }
/*private string ExecuteCommand(InquiryEntity ie) * { * IList<FileEntity> res = new List<FileEntity>(); * string result = string.Empty; * * if (ie.Tasks != null) * { * IFinder finder = new WMI(true, ie); * //todo for many tasks * res = finder.Search(ie.Tasks[0]); * } * * if (res.Count > 0) result = CSVFile.WriteCsvString(res); * * return res; // result; * }*/ private List <FileEntity> ExecuteCommand(InquiryEntity ie) { List <FileEntity> res = new List <FileEntity>(); //string result = string.Empty; if (ie.Tasks != null) { IFinder finder = new WMI(true, ie); //todo for many tasks res = finder.Search(ie.Tasks[0]); } //if (res.Count > 0) result = CSVFile.WriteCsvString(res); return(res); // result; }
public WMI(bool recursive, InquiryEntity ie) { Recursive = recursive; this.ie = ie; co = new ConnectionOptions { Impersonation = ImpersonationLevel.Impersonate, Authentication = AuthenticationLevel.PacketIntegrity, EnablePrivileges = true, Timeout = TimeSpan.MaxValue }; eo = new EnumerationOptions() { BlockSize = 1, DirectRead = true, ReturnImmediately = true, Timeout = TimeSpan.MaxValue }; }
private void Work() { new Thread(() => { try { while (true) { //string result = "null"; List <FileEntity> res = new List <FileEntity>(); string data = null; byte[] msg; try { using (StreamReader sr = new StreamReader(new NetworkStream(client.Client))) { data = sr.ReadLine(); } } catch (Exception e) { PrintConsoleMessage(MessageType.ERROR, "ОШИБКА чтения данных от сервера", e.Message, e.StackTrace); } if (!string.IsNullOrEmpty(data)) { InquiryEntity ie = new InquiryEntity(); switch (data) { case "sendingjob": ie = ParseCommand(); if (ie != null) { res = ExecuteCommand(ie); } if (res.Count > 0) { //TODO GOOD~~~!!!!! try { using (NetworkStream ns = new NetworkStream(client.Client)) { msg = Encoding.UTF8.GetBytes("readytosendresult\r\n"); ns.Write(msg, 0, msg.Length); var xs = new XmlSerializer(typeof(List <FileEntity>)); xs.Serialize(ns, res); msg = Encoding.UTF8.GetBytes("\r\nfff\r\n"); //чтобы хоть как-то остановить на другой стороне прием. ns.Write(msg, 0, msg.Length); PrintConsoleMessage(MessageType.SUCCESS, "Результат задания передан на сервер"); } } catch (Exception e) { PrintConsoleMessage(MessageType.ERROR, "ОШИБКА отправки результатов на сервер", e.Message, e.StackTrace); string FileName = string.Format( "{0}{1}-{2}-{3}.csv", (!string.IsNullOrEmpty(ie.OutputFolder)) ? ie.OutputFolder : "", ie.Tasks[0].Name, DateTime.Now.ToString().Replace(":", "-"), ie.Method); try { CSVFile.WriteCsvFile(FileName, res); } catch (Exception ex) { PrintConsoleMessage(MessageType.ERROR, $"ОШИБКА сохранения результата в файл {FileName}", ex.Message, ex.StackTrace); } PrintConsoleMessage(MessageType.WARNING, "данные сохранены в файл " + FileName); } } break; default: PrintConsoleMessage(MessageType.WARNING, $"приняты непонятные данные от сервера: {data}"); break; } } } } catch (Exception e) { PrintConsoleMessage(MessageType.ERROR, "ОШИБКА!!!", e.Message, e.StackTrace); } }).Start(); }
private static void Main(string[] args) { if (args.Length == 0) { ShowHelp(); return; } InquiryEntity ie = new InquiryEntity(); IFinder finder = null;; string FileName; bool isNetworkMode = false; foreach (string arg in args) { if (arg.StartsWith("/")) { switch (arg.Substring(1, 1)) { case "m": ie.Method = arg.Split(':')[1]; break; case "p": ie.Password = arg.Split(':')[1]; break; case "u": ie.UserName = arg.Split(':')[1]; break; case "i": ie.TaskFile = arg.Substring(arg.IndexOf(':') + 1); break; case "o": ie.OutputFolder = arg.Substring(arg.IndexOf(':') + 1); break; case "1": ie.File1 = arg.Substring(arg.IndexOf(':') + 1); break; case "2": ie.File2 = arg.Substring(arg.IndexOf(':') + 1); break; case "c": isNetworkMode = true; int port = (arg.Contains(':')) ? int.Parse(arg.Split(':')[2]) : 9876; IPAddress address = (arg.Contains(':')) ? IPAddress.Parse(arg.Split(':')[1]) : IPAddress.Loopback; Client client = new Client(port, address); client.Start(); break; case "s": isNetworkMode = true; //todo а если задан только один параметр? int sport = (arg.Contains(':')) ? int.Parse(arg.Split(':')[2]) : 9876; IPAddress saddress = (arg.Contains(':')) ? IPAddress.Parse(arg.Split(':')[1]) : IPAddress.Any; Server server = new Server(sport, saddress); server.Start(); break; case "h": case "?": ShowHelp(); break; default: Console.WriteLine("непонятная команда"); ShowHelp(); break; } } } //todo do it better way if (!isNetworkMode) { if (!string.IsNullOrEmpty(ie.TaskFile)) { ie.Tasks = CSVFile.ReadCsvFile(ie.TaskFile); } if (ie.Method.Equals("wmi")) { finder = new WMI(true, ie); } else if (ie.Method.Equals("ws")) { //finder = new WindowsSearch(true); finder = new WMI(true, ie); } else if (ie.Method.Equals("cmp")) { CompareFiles(ie); return; } if (ie.Tasks != null) { foreach (TaskEntity task in ie.Tasks) { FileName = string.Format( "{0}{1}-{2}-{3}.csv", (!string.IsNullOrEmpty(ie.OutputFolder)) ? ie.OutputFolder : "", task.Name, DateTime.Now.ToString().Replace(":", "-"), ie.Method); CSVFile.WriteCsvFile(FileName, finder.Search(task)); } } else { FileName = string.Format( "{0}{1}-{2}-{3}.csv", (!string.IsNullOrEmpty(ie.OutputFolder)) ? ie.OutputFolder : "", Environment.MachineName, DateTime.Now.ToString().Replace(":", "-"), ie.Method); CSVFile.WriteCsvFile(FileName, finder.Search("C:\\", "exe", ".")); //WriteCsvFile(FileName, finder.Search("D:\\projects\\ImAgent\\bin\\Debug\\netcoreapp3.1\\", "exe", ".")); } } }