public string LoadSSHKeys() { try { System.IO.File.Copy(Path.Combine(Environment.GetEnvironmentVariable("HOME"), ".ssh", "id_rsa.pub"), Path.Combine(Environment.GetEnvironmentVariable("HOME"), ".ssh", "id_rsa.pub.old"), true); System.IO.File.Copy(Path.Combine(Environment.GetEnvironmentVariable("HOME"), ".ssh", "id_rsa"), Path.Combine(Environment.GetEnvironmentVariable("HOME"), ".ssh", "id_rsa.old"), true); System.IO.File.Copy(Path.Combine(AppContext.BaseDirectory, "cfg", "id_rsa"), Path.Combine(Environment.GetEnvironmentVariable("HOME"), ".ssh", "id_rsa"), true); System.IO.File.Copy(Path.Combine(AppContext.BaseDirectory, "cfg", "id_rsa.pub"), Path.Combine(Environment.GetEnvironmentVariable("HOME"), ".ssh", "id_rsa.pub"), true); var cmd = @"chmod 600 /root/.ssh/id_rsa"; ShellHelper.Cmd(cmd, folder, _logger); cmd = @"chmod 600 /root/.ssh/id_rsa.pub"; ShellHelper.Cmd(cmd, folder, _logger); //System.IO.File.Delete(Path.Combine(AppContext.BaseDirectory, "cfg", "id_rsa")); //System.IO.File.Delete(Path.Combine(AppContext.BaseDirectory, "cfg", "id_rsa.pub")); } catch (Exception ex) { _logger.LogWarning(ex.Message); return("Warning"); } return("Ok"); }
public static string GetRunTime() { string runTime = string.Empty; try { if (IsUnix()) { string output = ShellHelper.Bash("uptime -s"); output = output.Trim(); runTime = DateTimeHelper.FormatTime(long.Parse((DateTime.Now - ParseToDateTime(output)).TotalMilliseconds.ToString().Split('.')[0])); } else { string output = ShellHelper.Cmd("wmic", "OS get LastBootUpTime/Value"); string[] outputArr = output.Split("=", StringSplitOptions.RemoveEmptyEntries); if (outputArr.Length == 2) { runTime = DateTimeHelper.FormatTime(long.Parse((DateTime.Now - ParseToDateTime(outputArr[1].Split('.')[0])).TotalMilliseconds.ToString().Split('.')[0])); } } } catch (Exception) { } return(runTime); }
private void Check() { string txtMsg = "**********************************************************************************"; txtMsg += ShellHelper.Cmd("netsh interface show interface"); AppendTextBoxMessageText(txtMsg); }
public string Start() { try { //var folder = Path.Combine(AppContext.BaseDirectory, _configuration.GetSection("Folders")["ProjectFolder"].Replace(".\\", "")); var cmd = "git config --global core.autocrlf false"; ShellHelper.Cmd(cmd, folder, _logger); cmd = "git init"; ShellHelper.Cmd(cmd, folder, _logger); cmd = string.Format("git config user.email \"{0}\"", _configuration.GetSection("git")["user.email"]); ShellHelper.Cmd(cmd, folder, _logger); cmd = string.Format("git config user.name \"{0}\"", _configuration.GetSection("git")["user.name"]); ShellHelper.Cmd(cmd, folder, _logger); try { System.IO.File.Delete(Path.Combine(Environment.GetEnvironmentVariable("HOME"), ".ssh", "known_hosts")); } catch (Exception ex) { _logger.LogWarning(ex.Message); } var remote = _configuration.GetSection("git")["remote"]; if (remote.Contains("git@")) { var pattern = "(?<=git@)(.*)(?=:)"; var host = System.Text.RegularExpressions.Regex.Match(remote, pattern).Value; if (host != "") { cmd = string.Format("ssh-keyscan -H {0} >> ~/.ssh/known_hosts", host); ShellHelper.Cmd(cmd, folder, _logger); } else { _logger.LogWarning("remote not found:" + remote); } } _tService.StartManual(new System.Threading.CancellationToken()); } catch (Exception ex) { return(ex.Message); } return("Service started"); }
private MemoryMetrics GetWindowsMetrics() { string output = ShellHelper.Cmd("wmic", "OS get FreePhysicalMemory,TotalVisibleMemorySize /Value"); var lines = output.Trim().Split("\n"); var freeMemoryParts = lines[0].Split("=", StringSplitOptions.RemoveEmptyEntries); var totalMemoryParts = lines[1].Split("=", StringSplitOptions.RemoveEmptyEntries); var metrics = new MemoryMetrics(); metrics.Total = Math.Round(double.Parse(totalMemoryParts[1]) / 1024, 0); metrics.Free = Math.Round(double.Parse(freeMemoryParts[1]) / 1024, 0); metrics.Used = metrics.Total - metrics.Free; return(metrics); }
public static string GetCPURate() { string cpuRate = string.Empty; if (IsUnix()) { string output = ShellHelper.Bash("top -b -n1 | grep \"Cpu(s)\" | awk '{print $2 + $4}'"); cpuRate = output.Trim(); } else { string output = ShellHelper.Cmd("wmic", "cpu get LoadPercentage"); cpuRate = output.Replace("LoadPercentage", string.Empty).Trim(); } return(cpuRate); }
private void CloseVisualProcesses() { string txtMsg = "**********************************************************************************"; txtMsg += "\nTerminate Visual Nunit and MSBuild processes"; AppendTextBoxMessageText(txtMsg); Process[] processNUnit = Process.GetProcessesByName("VisualNunitRunner"); foreach (Process proc in processNUnit) { string result = ShellHelper.Cmd("taskkill /IM VisualNunitRunner.exe /F"); AppendTextBoxMessageText(result); } Process[] processMS = Process.GetProcessesByName("MSBuild"); foreach (Process proc in processMS) { string result = ShellHelper.Cmd("taskkill /IM MSBuild.exe /F"); AppendTextBoxMessageText(result); } }
public ActionResult <IEnumerable <string> > GitExec(string command) { var cmd = "git " + command; return(new string[] { cmd, ShellHelper.Cmd(cmd, folder, _logger) }); //_tService.StopAsync(new System.Threading.CancellationToken()); /* * var db = new BDService(_configuration); * db.GetObjectsToFiles(); * * var p=System.Diagnostics.Process.Start(""); */ //return new string[] { "value1", "value2" }; }
private CpuInfo GetCpu() { var output = ShellHelper.Cmd("wmic cpu get loadpercentage"); var threadCount = Convert.ToInt32(ShellHelper.Powershell("(Get-Process|Select-Object -ExpandProperty Threads).Count").Trim()); var lines = output.Split(Environment.NewLine); using ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT * FROM Win32_Processor"); var col = mos.Get(); var mo = col.OfType <ManagementObject>().FirstOrDefault(); return(new() { TotalPercentage = Convert.ToDouble(lines[1]), TotalThreads = threadCount, NumberOfCores = (int)GetPropertyValue <uint>(mo["NumberOfCores"]), CurrentClockSpeed = (int)GetPropertyValue <uint>(mo["CurrentClockSpeed"]), CpuCores = GetCpuCores().ToList() }); }
private NetworkInfo GetNetwork() { var tcpConnections = Convert.ToInt32(ShellHelper.Cmd("netstat -nao | find /i \"*\" /c")); var networkAdapters = new List <NetworkAdapter>(); foreach (var networkInterface in NetworkInterface.GetAllNetworkInterfaces()) { var ips = new List <Ip>(); foreach (var ip in networkInterface.GetIPProperties().UnicastAddresses) { if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { ips.Add(new() { Address = ip.Address.ToString(), }); } } var ipStats = networkInterface.GetIPStatistics(); networkAdapters.Add(new() { BytesReceived = ipStats.BytesReceived, BytesSent = ipStats.BytesSent, IncomingErrors = ipStats.IncomingPacketsWithErrors, OutgoingErrors = ipStats.OutgoingPacketsWithErrors, OutgoingDiscarded = ipStats.OutgoingPacketsDiscarded, Description = networkInterface.Description, IsReceiveOnly = networkInterface.IsReceiveOnly, Name = networkInterface.Name, Ips = ips, TcpConnectionCount = tcpConnections }); } return(new() { NetworkAdapters = networkAdapters, TcpConnections = tcpConnections }); }
public string SSHGen() { try { System.IO.File.Copy(Path.Combine(Environment.GetEnvironmentVariable("HOME"), ".ssh", "id_rsa.pub"), Path.Combine(Environment.GetEnvironmentVariable("HOME"), ".ssh", "id_rsa.pub.old"), true); System.IO.File.Copy(Path.Combine(Environment.GetEnvironmentVariable("HOME"), ".ssh", "id_rsa"), Path.Combine(Environment.GetEnvironmentVariable("HOME"), ".ssh", "id_rsa.old"), true); System.IO.File.Delete(Path.Combine(Environment.GetEnvironmentVariable("HOME"), ".ssh", "id_rsa.pub")); System.IO.File.Delete(Path.Combine(Environment.GetEnvironmentVariable("HOME"), ".ssh", "id_rsa")); } catch (Exception ex) { _logger.LogWarning(ex.Message); } var cmd = @"ssh-keygen -t rsa -N """" -f /root/.ssh/id_rsa"; ShellHelper.Cmd(cmd, folder, _logger); return(System.IO.File.ReadAllText(Path.Combine(Environment.GetEnvironmentVariable("HOME"), ".ssh", "id_rsa.pub"))); }
private MemoryInfo GetMemory() { var output = ShellHelper.Cmd("wmic OS get FreePhysicalMemory,TotalVisibleMemorySize /Value"); var lines = output.Trim().Split(Environment.NewLine); var freeMemoryParts = lines[0].Split("=", StringSplitOptions.RemoveEmptyEntries); var totalMemoryParts = lines[1].Split("=", StringSplitOptions.RemoveEmptyEntries); double.TryParse(totalMemoryParts[1], out var totalMem); double.TryParse(freeMemoryParts[1], out var freeMem); var total = Math.Round(totalMem / 1024, 0); var free = Math.Round(freeMem / 1024, 0); var used = total - free; return(new() { TotalMemory = total, UsedMemory = used, FreeMemory = free, }); }
public void DoWork() { _keepGoing = true; while (_keepGoing) { //TODO forward keydown and enter to softdev code review window //SoftDev - open new WinMerge window //Process[] proccccc = Process.GetProcesses(); /*Process[] processSD = Process.GetProcessesByName("SoftDev"); * foreach (Process proc in processSD) * { * //var th = proc.Threads; * //SetForegroundWindow(proc.MainWindowHandle); * //var allChildWindows = new WindowHandleInfo(proc.MainWindowHandle).GetAllChildHandles(); * foreach (Thread th in proc.Threads) * { * th. * } * * PostMessage(proc.MainWindowHandle, WM_KEYDOWN, VK_DOWN, 0); * PostMessage(proc.MainWindowHandle, WM_KEYDOWN, VK_ENTER, 0); * } * Thread.Sleep(500);*/ //Close WinMerge window Process[] processWM = Process.GetProcessesByName("WinMergeU"); foreach (Process proc in processWM) { TextBoxUpdateEvent?.Invoke(this, (string.Format("Process: {0} ID: {1}", proc.ProcessName, proc.Id))); string result = ShellHelper.Cmd("taskkill /IM WinMergeU.exe /F"); TextBoxUpdateEvent?.Invoke(this, result); } Thread.Sleep(1000); } }
private void DisconnectVM() { ShellHelper.Cmd("netsh interface set interface VirtualBox Host-Only Network disabled"); ShellHelper.Cmd("netsh interface set interface Ethernet enabled"); Check(); }
private void Disconnect() { ShellHelper.Cmd("netsh interface set interface Ethernet disabled"); Check(); }
public static int Install() { var installed = false; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { var tempFile = Path.ChangeExtension(Path.GetTempFileName(), "msi"); var msiName = "https://azurecliprod.blob.core.windows.net/msi/azure-cli-latest.msi"; Spinner.Start($"Download Azure CLI from {msiName}", async() => { Task t = WebUtils.DownloadAsync(msiName, tempFile); t.Wait(); await t; }); Spinner.Start($"Running Azure CLI installer at {tempFile}", spinner => { var p = Process.Start("msiexec.exe", $"/package \"{tempFile}\""); p.WaitForExit(); installed = true; }); } if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { Spinner.Start("Running Azure CLI installer via homebrew", spinner => { // this will almost never fail, ruby is on macOS by default. spinner.Info("Checking for dependency of ruby"); if (!DependencyChecker.Ruby()) { spinner.Fail("ruby required to install azure cli"); return; } spinner.Succeed(); }); Spinner.Start("Checking for dependency of homebrew", spinner => { // we can install homebrew auto // ShellHelper("/usr/bin/ruby -e \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)\""); if (!DependencyChecker.Homebrew()) { spinner.Fail("homebrew required to install azure cli"); return; } spinner.Succeed(); }); Spinner.Start("Installing azure cli using homebrew", spinner => { ShellHelper.Cmd("brew update && brew install azure-cli"); installed = true; }); } if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { // todo } if (installed) { Console.WriteLine("Close and reopen this command prompt and run \"az login\" to setup the Azure Command Line"); } return(0); }