stop services

This commit is contained in:
2021-11-01 17:53:55 +02:00
parent 9521abd8d7
commit f774509b9d
2 changed files with 145 additions and 192 deletions

View File

@@ -1 +1 @@
No RunNetwork

View File

@@ -6,26 +6,61 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Linq; using System.Linq;
using System.ServiceProcess;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
namespace NetWork namespace NetWork {
{ class Program {
class Program public static void Servicer(string[] service, bool stop = true) {
{ foreach (string s in service) {
public static bool Earphones() Servicer(s, stop);
{ }
}
private static ServiceController[] GetServices(string service) {
Regex regex = new(service, RegexOptions.IgnoreCase);
List<ServiceController> ServiceList = new List<ServiceController>();
foreach (var services in ServiceController.GetServices()) {
if (regex.IsMatch(services.DisplayName)) {
ServiceList.Add(services);
}
}
return ServiceList.ToArray();
}
public static void Servicer(string service, bool stop = true) {
var Services = GetServices(service);
if (stop) {
foreach (var ser in Services) {
try {
ser.Stop();
} catch {
}
}
} else {
foreach (var ser in Services) {
try {
ser.Start();
} catch {
}
}
}
}
public static bool Earphones() {
string data = System.IO.File.ReadAllText($"{AppDomain.CurrentDomain.BaseDirectory}\\Other\\earphones.json"); string data = System.IO.File.ReadAllText($"{AppDomain.CurrentDomain.BaseDirectory}\\Other\\earphones.json");
#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. #pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type.
dynamic array = (JArray)Newtonsoft.Json.JsonConvert.DeserializeObject(data, typeof(JArray)); dynamic array = (JArray)Newtonsoft.Json.JsonConvert.DeserializeObject(data, typeof(JArray));
#pragma warning restore CS8600 // Converting null literal or possible null value to non-nullable type. #pragma warning restore CS8600 // Converting null literal or possible null value to non-nullable type.
var device = new MMDeviceEnumerator(); var device = new MMDeviceEnumerator();
var Devices = device.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active); var Devices = device.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active);
foreach (var Device in Devices) foreach (var Device in Devices) {
{ foreach (string ob in array) {
foreach (string ob in array) if (Device.FriendlyName.Contains(ob)) {
{
if (Device.FriendlyName.Contains(ob))
{
return true; return true;
} }
@@ -33,8 +68,7 @@ namespace NetWork
} }
return false; return false;
} }
public static Logger StartLogger() public static Logger StartLogger() {
{
var config = new NLog.Config.LoggingConfiguration(); var config = new NLog.Config.LoggingConfiguration();
var logfile = new NLog.Targets.FileTarget("lgfle") { FileName = "logme.txt" }; var logfile = new NLog.Targets.FileTarget("lgfle") { FileName = "logme.txt" };
config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile); config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);
@@ -54,44 +88,32 @@ namespace NetWork
/// This Function Stops the RDP connection to the office computer. it takes 'stop' parameter. if it is true, it stops the rdp. otherwise, it starts it. /// This Function Stops the RDP connection to the office computer. it takes 'stop' parameter. if it is true, it stops the rdp. otherwise, it starts it.
/// </summary> /// </summary>
/// <param name="stop">A bool parameter. it swiches between stopping (default) and starting rdp session.</param> /// <param name="stop">A bool parameter. it swiches between stopping (default) and starting rdp session.</param>
public static void StopRDP(bool stop = true) public static void StopRDP(bool stop = true) {
{
if (stop) if (stop) {
{
Process[] ids = Process.GetProcessesByName("mstsc"); Process[] ids = Process.GetProcessesByName("mstsc");
foreach (var id in ids) foreach (var id in ids) {
{
logger.Debug(id.MainWindowTitle); logger.Debug(id.MainWindowTitle);
Regex rdp = new("(משרדוש.rdp|161.2)"); Regex rdp = new("(משרדוש.rdp|161.2)");
if (rdp.IsMatch(id.MainWindowTitle) || id.MainWindowTitle.Equals("חיבור לשולחן עבודה מרוחק")) if (rdp.IsMatch(id.MainWindowTitle) || id.MainWindowTitle.Equals("חיבור לשולחן עבודה מרוחק")) {
{
id.Kill(); id.Kill();
} }
Console.WriteLine(""); Console.WriteLine("");
} }
} } else {
else
{
Process[] ids = Process.GetProcessesByName("mstsc"); Process[] ids = Process.GetProcessesByName("mstsc");
if (ids.Length < 1) if (ids.Length < 1) {
{
StartProgram("rdp"); StartProgram("rdp");
} } else {
else
{
bool started = false; bool started = false;
foreach (var id in ids) foreach (var id in ids) {
{
Regex rdp = new("(משרדוש.rdp|161.2)"); Regex rdp = new("(משרדוש.rdp|161.2)");
logger.Debug(id.MainWindowTitle); logger.Debug(id.MainWindowTitle);
if (rdp.IsMatch(id.MainWindowTitle) || id.MainWindowTitle.Equals("חיבור לשולחן עבודה מרוחק")) if (rdp.IsMatch(id.MainWindowTitle) || id.MainWindowTitle.Equals("חיבור לשולחן עבודה מרוחק")) {
{
started = true; started = true;
} }
} }
if (!started) if (!started) {
{
StartProgram("rdp"); StartProgram("rdp");
} }
@@ -105,10 +127,8 @@ namespace NetWork
/// </summary> /// </summary>
/// <param name="connect"></param> /// <param name="connect"></param>
/// <returns></returns> /// <returns></returns>
public static bool Dial(bool connect = true) public static bool Dial(bool connect = true) {
{ if (connect) {
if (connect)
{
RasDialer rasDialer = new(); RasDialer rasDialer = new();
rasDialer.AllowUseStoredCredentials = true; rasDialer.AllowUseStoredCredentials = true;
rasDialer.PhoneBookPath = @"D:\Drive\טוויקים למחשב\סקריפטוש\C#\NetWork\NetWork\Other\ek.pbk"; rasDialer.PhoneBookPath = @"D:\Drive\טוויקים למחשב\סקריפטוש\C#\NetWork\NetWork\Other\ek.pbk";
@@ -123,8 +143,7 @@ namespace NetWork
/// </summary> /// </summary>
/// <param name="NameOrPath">file or path of the program</param> /// <param name="NameOrPath">file or path of the program</param>
/// <returns>path if name has given, name if path has given. empty string if found nothing.</returns> /// <returns>path if name has given, name if path has given. empty string if found nothing.</returns>
public static string GetProgram(string NameOrPath) public static string GetProgram(string NameOrPath) {
{
/* /*
this function decides if the program is a name, or a location. this function decides if the program is a name, or a location.
if it is a location, it returns the name of the program if it is a location, it returns the name of the program
@@ -132,82 +151,57 @@ namespace NetWork
otherwise, it returns empty string otherwise, it returns empty string
*/ */
if (progs.ContainsKey(NameOrPath)) if (progs.ContainsKey(NameOrPath)) {
{
return progs[NameOrPath]; return progs[NameOrPath];
} }
if (paths.ContainsKey(NameOrPath)) if (paths.ContainsKey(NameOrPath)) {
{
return paths[NameOrPath]; return paths[NameOrPath];
} }
return ""; return "";
} }
public static void StopSurfshark() public static void StopSurfshark() {
{
Process.GetProcesses() Process.GetProcesses()
.Where(x => x.ProcessName.StartsWith("surf", StringComparison.OrdinalIgnoreCase)) .Where(x => x.ProcessName.StartsWith("surf", StringComparison.OrdinalIgnoreCase))
.ToList() .ToList()
.ForEach(x => x.Kill()); .ForEach(x => x.Kill());
} }
public static void StopProgram(string[] Name, bool mute = true) public static void StopProgram(string[] Name, bool mute = true) {
{ foreach (string name in Name) {
foreach (string name in Name) try {
{
try
{
System.Text.RegularExpressions.Regex vpnRegEx = new(@"[Ss][Uu][Rr][Ff][Ss][Hh][Aa][Rr][Kk]"); System.Text.RegularExpressions.Regex vpnRegEx = new(@"[Ss][Uu][Rr][Ff][Ss][Hh][Aa][Rr][Kk]");
if (vpnRegEx.IsMatch(name)) if (vpnRegEx.IsMatch(name)) {
{
StopSurfshark(); StopSurfshark();
} } else if (progs.ContainsKey(name)) {
else if (progs.ContainsKey(name))
{
Process[] p = Process.GetProcessesByName(name); Process[] p = Process.GetProcessesByName(name);
foreach (Process proc in p) foreach (Process proc in p) {
{
proc.Kill(true); proc.Kill(true);
} }
} } else {
else if (name.Contains("mstsc") || name.Contains("rdp")) {
{
if (name.Contains("mstsc") || name.Contains("rdp"))
{
StopRDP(); StopRDP();
} }
} }
} } catch {
catch
{
continue; continue;
} }
} }
MuteSystem(mute); MuteSystem(mute);
} }
public static void StartProgram(string[] Name, bool mute = false) public static void StartProgram(string[] Name, bool mute = false) {
{ foreach (var process_name in Name) {
foreach (var process_name in Name) if (process_name.Contains("rdp") || process_name.Contains("mstsc")) {
{
if (process_name.Contains("rdp") || process_name.Contains("mstsc"))
{
StopRDP(false); StopRDP(false);
continue; continue;
} } else if (Process.GetProcessesByName(process_name).Length < 1) {
else if (Process.GetProcessesByName(process_name).Length < 1)
{
string process; string process;
if (progs.ContainsKey(process_name)) if (progs.ContainsKey(process_name)) {
{
process = progs[process_name]; process = progs[process_name];
} } else if (paths.ContainsKey(process_name)) {
else if (paths.ContainsKey(process_name))
{
process = process_name; process = process_name;
} } else {
else
{
process = @"C:\Windows\System32\rundll32.exe"; process = @"C:\Windows\System32\rundll32.exe";
} }
Process.Start(process); Process.Start(process);
@@ -215,64 +209,50 @@ namespace NetWork
} }
MuteSystem(mute); MuteSystem(mute);
} }
public static string GetWifiNetwork() public static string GetWifiNetwork() {
{
SimpleWifi.Win32.WlanClient wlan = new(); SimpleWifi.Win32.WlanClient wlan = new();
string wifiname; string wifiname;
try try {
{
wifiname = wlan.Interfaces[0].CurrentConnection.profileName; wifiname = wlan.Interfaces[0].CurrentConnection.profileName;
} } catch {
catch
{
wifiname = ""; wifiname = "";
} }
return wifiname; return wifiname;
} }
public static bool? IsItGoodWifi(string currentWifi) public static bool? IsItGoodWifi(string currentWifi) {
{
Regex regex = new(currentWifi); Regex regex = new(currentWifi);
bool? goodWifi; bool? goodWifi;
goodWifi = regex.IsMatch("Oliver Oliver5 Oliver x018_497622 TNCAPE5A34D MSBR Azrieli_Modiin_WIFI lu shalmata mickey Mickey Network 192.168.1. Silmarill wintunshark0 saret Saret huji-meonot") ? true : (regex.IsMatch("HUJI-netX eduroam HUJI-guest 132.64") ? false : null); goodWifi = regex.IsMatch("Oliver Oliver5 Oliver x018_497622 TNCAPE5A34D MSBR Azrieli_Modiin_WIFI lu shalmata mickey Mickey Network 192.168.1. Silmarill wintunshark0 saret Saret huji-meonot") ? true : (regex.IsMatch("HUJI-netX eduroam HUJI-guest 132.64") ? false : null);
return goodWifi; return goodWifi;
} }
static bool LanEthernet(System.Net.NetworkInformation.NetworkInterface networkAdapter) static bool LanEthernet(System.Net.NetworkInformation.NetworkInterface networkAdapter) {
{ if (networkAdapter.Name.Contains("Ethernet") || (networkAdapter.NetworkInterfaceType.ToString().Contains("Ethernet"))) {
if (networkAdapter.Name.Contains("Ethernet") || (networkAdapter.NetworkInterfaceType.ToString().Contains("Ethernet")))
{
return true; return true;
} }
return false; return false;
} }
static bool IgnoreLan(System.Net.NetworkInformation.NetworkInterface networkAdapter) static bool IgnoreLan(System.Net.NetworkInformation.NetworkInterface networkAdapter) {
{ if (!(networkAdapter.Name.Contains("Bluetooth")) && (!(networkAdapter.Description.Contains("TAP"))) && (!(networkAdapter.Description.Contains("Hyper-V")))) {
if (!(networkAdapter.Name.Contains("Bluetooth")) && (!(networkAdapter.Description.Contains("TAP"))) && (!(networkAdapter.Description.Contains("Hyper-V"))))
{
return true; return true;
} }
return false; return false;
} }
static string GetLan(System.Net.NetworkInformation.NetworkInterface networkAdapter) static string GetLan(System.Net.NetworkInformation.NetworkInterface networkAdapter) {
{ if (LanEthernet(networkAdapter) && IgnoreLan(networkAdapter)) {
if (LanEthernet(networkAdapter) && IgnoreLan(networkAdapter))
{
return networkAdapter.GetPhysicalAddress().ToString(); return networkAdapter.GetPhysicalAddress().ToString();
} }
return null; return null;
} }
static bool GetVpn(System.Net.NetworkInformation.NetworkInterface net) static bool GetVpn(System.Net.NetworkInformation.NetworkInterface net) {
{ if (net.Name.Contains("Surfshark") || net.Name.Contains("shark") || net.Description.Contains("TAP")) {
if (net.Name.Contains("Surfshark") || net.Name.Contains("shark") || net.Description.Contains("TAP"))
{
return net.OperationalStatus.ToString().Equals("Up"); return net.OperationalStatus.ToString().Equals("Up");
} }
return false; return false;
} }
public static Dictionary<string, dynamic> GetNetwork() public static Dictionary<string, dynamic> GetNetwork() {
{
Dictionary<string, dynamic> net_dict = new() { { "vpn", false }, { "lan", false }, { "good_lan", false }, { "ek", false } }; Dictionary<string, dynamic> net_dict = new() { { "vpn", false }, { "lan", false }, { "good_lan", false }, { "ek", false } };
System.Net.NetworkInformation.NetworkInterface[] nets = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces(); System.Net.NetworkInformation.NetworkInterface[] nets = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
string getlan = ""; string getlan = "";
@@ -280,189 +260,162 @@ namespace NetWork
bool getgoodland = false; bool getgoodland = false;
string? getwifi; string? getwifi;
getwifi = GetWifiNetwork(); getwifi = GetWifiNetwork();
foreach (var net in nets) foreach (var net in nets) {
{ if (net.Name == "ek") {
if (net.Name == "ek")
{
net_dict["ek"] |= true; net_dict["ek"] |= true;
} }
net_dict["vpn"] |= GetVpn(net); net_dict["vpn"] |= GetVpn(net);
lannull = GetLan(net); lannull = GetLan(net);
if (lannull is not null) if (lannull is not null) {
{
getlan = lannull; getlan = lannull;
} }
if (AllowedMac(net.GetPhysicalAddress().ToString())) if (AllowedMac(net.GetPhysicalAddress().ToString())) {
{
getgoodland |= true; getgoodland |= true;
} }
} }
net_dict.Add("Wi-Fi", IsItGoodWifi(getwifi)); net_dict.Add("Wi-Fi", IsItGoodWifi(getwifi));
net_dict["good_lan"] = getgoodland; net_dict["good_lan"] = getgoodland;
if (getlan.Length > 0) if (getlan.Length > 0) {
{
net_dict["lan"] = true; net_dict["lan"] = true;
} }
//net_dict.Add("good_lan", AllowedMac()); //net_dict.Add("good_lan", AllowedMac());
return net_dict; return net_dict;
} }
private static string HirarcyNetworks(Dictionary<string, dynamic> network_dictionary) private static string HirarcyNetworks(Dictionary<string, dynamic> network_dictionary) {
{ if (network_dictionary["vpn"]) {
if (network_dictionary["vpn"])
{
return "vpn"; return "vpn";
} } else if (network_dictionary["ek"]) {
else if (network_dictionary["ek"])
{
return "ek"; return "ek";
} } else if (network_dictionary["good_lan"]) {
else if (network_dictionary["good_lan"])
{
return "good_lan"; return "good_lan";
} } else if (network_dictionary["lan"]) {
else if (network_dictionary["lan"])
{
return "lan"; return "lan";
} }
return "Wi-Fi"; return "Wi-Fi";
} }
public static bool AllowedMac(string mac, string[] those_are_the_AllowedMacs = null) public static bool AllowedMac(string mac, string[] those_are_the_AllowedMacs = null) {
{
string[] AllowedMac_adresses; string[] AllowedMac_adresses;
if (!(those_are_the_AllowedMacs is null)) if (!(those_are_the_AllowedMacs is null)) {
{
AllowedMac_adresses = those_are_the_AllowedMacs; AllowedMac_adresses = those_are_the_AllowedMacs;
} } else {
else
{
AllowedMac_adresses = new string[] { "00E04C6813E4" }; AllowedMac_adresses = new string[] { "00E04C6813E4" };
} }
foreach (var mac_address in AllowedMac_adresses) foreach (var mac_address in AllowedMac_adresses) {
{ if (mac_address.Equals(mac)) {
if (mac_address.Equals(mac))
{
return true; return true;
} }
} }
return false; return false;
} }
public static bool AllowedMac(string[] mac, string[] those_are_the_AllowedMacs = null) public static bool AllowedMac(string[] mac, string[] those_are_the_AllowedMacs = null) {
{ foreach (var single_mac in mac) {
foreach (var single_mac in mac) if (AllowedMac(single_mac, those_are_the_AllowedMacs)) {
{
if (AllowedMac(single_mac, those_are_the_AllowedMacs))
{
return true; return true;
} }
} }
return false; return false;
} }
public static void StartProgram(string process_name) public static void StartProgram(string process_name) {
{ if (process_name.Contains("rdp") || process_name.Contains("mstsc")) {
if (process_name.Contains("rdp") || process_name.Contains("mstsc"))
{
Process.Start("mstsc.exe", @"D:\Drive\מסמכים\vms\משרדוש.rdp"); Process.Start("mstsc.exe", @"D:\Drive\מסמכים\vms\משרדוש.rdp");
} } else if (Process.GetProcessesByName(process_name).Length < 1) {
else if (Process.GetProcessesByName(process_name).Length < 1)
{
string process; string process;
if (progs.ContainsKey(process_name)) if (progs.ContainsKey(process_name)) {
{
process = progs[process_name]; process = progs[process_name];
} } else if (paths.ContainsKey(process_name)) {
else if (paths.ContainsKey(process_name))
{
process = process_name; process = process_name;
} } else {
else
{
process = @"C:\Windows\System32\rundll32.exe"; process = @"C:\Windows\System32\rundll32.exe";
} }
Process.Start(process); Process.Start(process);
} }
} }
public static void MuteSystem(bool mute = true) public static void MuteSystem(bool mute = true) {
{
MMDeviceEnumerator mMDeviceEnumerator = new(); MMDeviceEnumerator mMDeviceEnumerator = new();
mMDeviceEnumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia).AudioEndpointVolume.Mute = mute; mMDeviceEnumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia).AudioEndpointVolume.Mute = mute;
} }
public static void DoTheSchtik(bool Run) public static void DoTheSchtik(bool Run) {
{ if (Run) {
if (Run)
{
var network_connection = GetNetwork(); var network_connection = GetNetwork();
string[] programs_to_run; string[] programs_to_run;
string[] programs_to_stop; string[] programs_to_stop;
string[] services_to_stop = new string[] { };
string[] services_to_start = new string[] { };
bool mute; bool mute;
switch (HirarcyNetworks(network_connection)) switch (HirarcyNetworks(network_connection)) {
{
case "vpn": case "vpn":
programs_to_run = new string[] { "GoogleDriveFS", "qbittorrent", "Surfshark" }; programs_to_run = new string[] { "GoogleDriveFS", "qbittorrent", "Surfshark" };
programs_to_stop = new string[] { "rdp" }; programs_to_stop = new string[] { "rdp" };
services_to_start = new string[] { "Surf" };
mute = false; mute = false;
break; break;
case "ek": case "ek":
programs_to_run = new string[] { "rdp", "GoogleDriveFS" }; programs_to_run = new string[] { "rdp", "GoogleDriveFS" };
programs_to_stop = new string[] { "qbittorrent", "Surfshark" }; programs_to_stop = new string[] { "qbittorrent", "Surfshark" };
services_to_stop = new string[] { "Surf" };
mute = false; mute = false;
break; break;
case "good_lan": case "good_lan":
programs_to_run = new string[] { "GoogleDriveFS", "qbittorrent", "Surfshark" }; programs_to_run = new string[] { "GoogleDriveFS", "qbittorrent", "Surfshark" };
services_to_start = new string[] { "Surf" };
programs_to_stop = new string[] { "rdp" }; programs_to_stop = new string[] { "rdp" };
mute = false; mute = false;
break; break;
case "lan": case "lan":
programs_to_run = new string[] { "rdp", "GoogleDriveFS" }; programs_to_run = new string[] { "rdp", "GoogleDriveFS" };
programs_to_stop = new string[] { "qbittorrent", "Surfshark" }; programs_to_stop = new string[] { "qbittorrent", "Surfshark" };
services_to_stop = new string[] { "Surf" };
mute = false; mute = false;
Dial(true); Dial(true);
break; break;
default: default:
if (network_connection["Wi-Fi"]) if (network_connection["Wi-Fi"]) {
{
programs_to_run = new string[] { "GoogleDriveFS", "qbittorrent", "Surfshark" }; programs_to_run = new string[] { "GoogleDriveFS", "qbittorrent", "Surfshark" };
services_to_start = new string[] { "Surf" };
programs_to_stop = new string[] { "rdp" }; programs_to_stop = new string[] { "rdp" };
mute = false; mute = false;
break; break;
} } else {
else
{
programs_to_run = new string[] { "GoogleDriveFS" }; programs_to_run = new string[] { "GoogleDriveFS" };
programs_to_stop = new string[] { "qbittorrent", "Surfshark", "rdp" }; programs_to_stop = new string[] { "qbittorrent", "Surfshark", "rdp" };
services_to_stop = new string[] { "Surf" };
mute = true; mute = true;
} }
break; break;
} }
if (Earphones()) if (Earphones()) {
{
mute = false; mute = false;
} }
if (programs_to_run is not null) if (programs_to_run is not null) {
{
StartProgram(programs_to_run, mute); StartProgram(programs_to_run, mute);
MuteSystem(mute); MuteSystem(mute);
} }
if (programs_to_stop is not null) if (programs_to_stop is not null) {
{
StopProgram(programs_to_stop, mute); StopProgram(programs_to_stop, mute);
MuteSystem(mute); MuteSystem(mute);
} }
if (services_to_start.Length > 0) {
Servicer(services_to_start, false);
}
if (services_to_stop.Length > 0) {
Servicer(services_to_stop);
}
} }
System.Windows.Forms.Application.Exit(); System.Windows.Forms.Application.Exit();
} }
public static bool IniData() public static bool IniData() {
{
return System.IO.File.ReadAllText("D:\\Drive\\טוויקים למחשב\\סקריפטוש\\C#\\NetWork\\NetWork\\Other\\Data.ini").Equals("RunNetwork"); return System.IO.File.ReadAllText("D:\\Drive\\טוויקים למחשב\\סקריפטוש\\C#\\NetWork\\NetWork\\Other\\Data.ini").Equals("RunNetwork");
} }
static void Main(string[] args) static void Main(string[] args) {
{
logger.Debug("me"); logger.Debug("me");
//IgnoreFile.M(); //IgnoreFile.M();
DoTheSchtik(IniData()); DoTheSchtik(IniData());