public async Task WithInvalidParams_ReturnsProcessError() { var data = await ProcessRunner.GetProcessOutputAsync("dotnet", "lol"); Assert.IsNotEmpty(data); Assert.IsTrue(data.StartsWith("No executable found")); }
public async Task WithValidParamsAndTempDirectory_ReturnsProcessOutput() { var data = await ProcessRunner.GetProcessOutputAsync("dotnet", "--help", System.IO.Path.GetTempPath()); Assert.IsNotEmpty(data); Assert.IsTrue(data.StartsWith(".NET Command Line Tools")); }
/// <summary> /// Setups the wireless network. /// </summary> /// <param name="adapterName">Name of the adapter.</param> /// <param name="networkSsid">The network ssid.</param> /// <param name="password">The password.</param> /// <param name="countryCode">The 2-letter country code in uppercase. Default is US.</param> /// <returns>True if successful. Otherwise, false.</returns> public async Task <bool> SetupWirelessNetwork(string adapterName, string networkSsid, string password = null, string countryCode = "US") { // TODO: Get the country where the device is located to set 'country' param in payload var var payload = $"country={countryCode}\nctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev\nupdate_config=1\n"; payload += string.IsNullOrEmpty(password) ? $"network={{\n\tssid=\"{networkSsid}\"\n\t}}\n" : $"network={{\n\tssid=\"{networkSsid}\"\n\tpsk=\"{password}\"\n\t}}\n"; try { File.WriteAllText("/etc/wpa_supplicant/wpa_supplicant.conf", payload); await ProcessRunner.GetProcessOutputAsync("pkill", "-f wpa_supplicant"); await ProcessRunner.GetProcessOutputAsync("ifdown", adapterName); await ProcessRunner.GetProcessOutputAsync("ifup", adapterName); } catch (Exception ex) { ex.Log(nameof(NetworkSettings)); return(false); } return(true); }
public async Task WithValidParams_ReturnsProcessOutput() { var data = await ProcessRunner.GetProcessOutputAsync("dotnet", "--help"); Assert.IsNotEmpty(data); Assert.IsTrue(data.StartsWith(".NET")); }
public async Task GetProcessOutputAsyncTest() { var data = await ProcessRunner.GetProcessOutputAsync("dotnet", "--help"); Assert.IsNotEmpty(data); Assert.IsTrue(data.StartsWith(".NET Command Line Tools")); }
/// <summary> /// Sets the device to re-pair automatically when it is turned on, which eliminates the need to pair all over again. /// </summary> /// <param name="controllerAddress">The mac address of the controller will be used.</param> /// <param name="deviceAddress">The mac address of the device will be added to the trust list devices.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// Returns true or false if the operation was successful. /// </returns> /// <exception cref="BluetoothErrorException">Failed to add to trust devices list:.</exception> public async Task <bool> Trust(string controllerAddress, string deviceAddress, CancellationToken cancellationToken = default) { try { // Selects the controller to pair. Once you select the controller, all controller-related commands will apply to it for three minutes. await ProcessRunner.GetProcessOutputAsync(BcCommand, $"select {controllerAddress}", cancellationToken).ConfigureAwait(false); // Makes the controller visible to other devices. await ProcessRunner.GetProcessOutputAsync(BcCommand, "discoverable on", cancellationToken).ConfigureAwait(false); // Readies the controller for pairing. Remember that you have three minutes after running this command to pair. await ProcessRunner.GetProcessOutputAsync(BcCommand, "pairable on", cancellationToken).ConfigureAwait(false); // Sets the device to re-pair automatically when it is turned on, which eliminates the need to pair all over again. var result = await ProcessRunner.GetProcessOutputAsync(BcCommand, $"trust {deviceAddress}", cancellationToken).ConfigureAwait(false); // Hides the controller from other Bluetooth devices. Otherwise, any device that can detect it has access to it, leaving a major security hole. await ProcessRunner.GetProcessOutputAsync(BcCommand, "discoverable off", cancellationToken).ConfigureAwait(false); return(result.Contains("Trusted: yes")); } catch (Exception ex) { throw new BluetoothErrorException($"Failed to add to trust devices list: {ex.Message}"); } }
/// <summary> /// Displays information about a particular device. /// </summary> /// <param name="deviceAddress">The mac address of the device which info will be retrieved.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// Returns the device info. /// </returns> /// <exception cref="BluetoothErrorException">Failed to retrieve info for {deviceAddress}.</exception> public async Task <string> DeviceInfo(string deviceAddress, CancellationToken cancellationToken = default) { var info = await ProcessRunner.GetProcessOutputAsync(BcCommand, $"info {deviceAddress}", cancellationToken) .ConfigureAwait(false); return(!string.IsNullOrEmpty(info) ? info : throw new BluetoothErrorException($"Failed to retrieve info for {deviceAddress}")); }
/// <summary> /// Retrieves the current network adapter. /// </summary> /// <returns>The name of the current network adapter.</returns> public static async Task <string> GetCurrentAdapterName() { var result = await ProcessRunner.GetProcessOutputAsync("route").ConfigureAwait(false); var defaultLine = result.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries) .FirstOrDefault(l => l.StartsWith("default", StringComparison.OrdinalIgnoreCase)); return(defaultLine?.Trim().Substring(defaultLine.LastIndexOf(" ", StringComparison.OrdinalIgnoreCase) + 1)); }
private static async Task <string> SetAudioCommand(string command, int cardNumber = DefaultCardNumber, string controlName = DefaultControlName) { var taskResult = await ProcessRunner.GetProcessOutputAsync("amixer", $"-q -c {cardNumber} -- set {controlName} {command}").ConfigureAwait(false); if (!string.IsNullOrWhiteSpace(taskResult)) { throw new InvalidOperationException(taskResult.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries).First()); } return(taskResult); }
/// <summary> /// Turns off the bluetooth adapter. /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// Returns true or false depending if the controller was turned off. /// </returns> /// <exception cref="BluetoothErrorException">Failed to power off:.</exception> public async Task <bool> PowerOff(CancellationToken cancellationToken = default) { try { var output = await ProcessRunner.GetProcessOutputAsync(BcCommand, "power off", cancellationToken).ConfigureAwait(false); return(output.Contains("succeeded")); } catch (Exception ex) { throw new BluetoothErrorException($"Failed to power off: {ex.Message}"); } }
/// <summary> /// Gets the list of bluetooth controllers. /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// Returns the list of bluetooth controllers. /// </returns> /// <exception cref="BluetoothErrorException">Failed to retrieve controllers:.</exception> public async Task <IEnumerable <string> > ListControllers(CancellationToken cancellationToken = default) { try { var controllers = await ProcessRunner.GetProcessOutputAsync(BcCommand, "list", cancellationToken).ConfigureAwait(false); return(controllers.Trim().Split('\n').Select(x => x.Trim())); } catch (Exception ex) { throw new BluetoothErrorException($"Failed to retrieve controllers: {ex.Message}"); } }
public Task <bool> GetStatus(WebServer server, HttpListenerContext context) { var nameList = new List <string>(); try { var interfacesOutput = ProcessRunner.GetProcessOutputAsync("ifconfig").Result; var outputLines = interfacesOutput.Split('\n').Where(x => string.IsNullOrWhiteSpace(x) == false).ToArray(); var name = string.Empty; foreach (var item in outputLines) { if (item[0] >= 'a' && item[0] <= 'z') { name = item.Substring(0, item.IndexOf(':')); } if (item.IndexOf("RX packets") == -1) { continue; } var packets = item.Substring(item.IndexOf("RX packets") + 11, 5); var index = packets.IndexOf(' '); var packetsValue = index != -1 ? int.Parse(packets.Substring(0, index)) : int.Parse(packets); if (packetsValue <= 0) { continue; } name = name.StartsWith("eth") ? "Wired" : name; name = name.StartsWith("wlan") ? "Wireless" : name; nameList.Add(name); } } catch (Exception) { // Empty } return(context.JsonResponseAsync(new { ConnectionType = nameList, PublicIP = Network.GetPublicIPAddress(), LocalIPs = Network.GetIPv4Addresses() })); }
/// <summary> /// Gets the list of detected devices. /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// Returns the list of detected devices. /// </returns> /// <exception cref="BluetoothErrorException">Failed to retrieve devices:.</exception> public async Task <IEnumerable <string> > ListDevices(CancellationToken cancellationToken = default) { try { using var cancellationTokenSource = new CancellationTokenSource(3000); await ProcessRunner.GetProcessOutputAsync(BcCommand, "scan on", cancellationTokenSource.Token).ConfigureAwait(false); await ProcessRunner.GetProcessOutputAsync(BcCommand, "scan off", cancellationToken).ConfigureAwait(false); var devices = await ProcessRunner.GetProcessOutputAsync(BcCommand, "devices", cancellationToken).ConfigureAwait(false); return(devices.Trim().Split('\n').Select(x => x.Trim())); } catch (Exception ex) { throw new BluetoothErrorException($"Failed to retrieve devices: {ex.Message}"); } }
/// <summary> /// Gets the current audio state. /// </summary> /// <param name="cardNumber">The card number.</param> /// <param name="controlName">Name of the control.</param> /// <returns>An <see cref="AudioState"/> object.</returns> /// <exception cref="InvalidOperationException">Invalid command, card number or control name.</exception> public async Task <AudioState> GetState(int cardNumber = DefaultCardNumber, string controlName = DefaultControlName) { var volumeInfo = await ProcessRunner.GetProcessOutputAsync("amixer", $"-c {cardNumber} get {controlName}").ConfigureAwait(false); var lines = volumeInfo.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); if (!lines.Any()) { throw new InvalidOperationException("Invalid command."); } if (_errorMess.Any(x => lines[0].Contains(x))) { throw new InvalidOperationException(lines[0]); } var volumeLine = lines .FirstOrDefault(x => x.Trim() .StartsWith("Mono:", StringComparison.OrdinalIgnoreCase)); if (volumeLine == null) { throw new InvalidOperationException("Unexpected output from 'amixer'."); } var sections = volumeLine.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); var level = int.Parse(sections[3].Substring(1, sections[3].Length - 3), System.Globalization.NumberFormatInfo.InvariantInfo); var decibels = float.Parse(sections[4].Substring(1, sections[4].Length - 4), System.Globalization.NumberFormatInfo.InvariantInfo); var isMute = sections[5].Equals("[off]", StringComparison.CurrentCultureIgnoreCase); return(new AudioState(cardNumber, controlName, level, decibels, isMute)); }
/// <summary> /// Retrieves the wireless networks. /// </summary> /// <param name="adapters">The adapters.</param> /// <returns>A list of WiFi networks</returns> public List <WirelessNetworkInfo> RetrieveWirelessNetworks(string[] adapters = null) { var result = new List <WirelessNetworkInfo>(); foreach (var networkAdapter in adapters ?? RetrieveAdapters().Where(x => x.IsWireless).Select(x => x.Name)) { var wirelessOutput = ProcessRunner.GetProcessOutputAsync("iwlist", $"{networkAdapter} scanning").Result; var outputLines = wirelessOutput.Split('\n') .Select(x => x.Trim()) .Where(x => string.IsNullOrWhiteSpace(x) == false) .ToArray(); for (var i = 0; i < outputLines.Length; i++) { var line = outputLines[i]; if (line.StartsWith(EssidTag) == false) { continue; } var network = new WirelessNetworkInfo() { Name = line.Replace(EssidTag, string.Empty).Replace("\"", string.Empty) }; while (true) { if (i + 1 >= outputLines.Length) { break; } // should look for two lines before the ESSID acording to the scan line = outputLines[i - 2]; if (line.StartsWith("Quality=")) { network.Quality = line.Replace("Quality=", string.Empty); break; } } while (true) { if (i + 1 >= outputLines.Length) { break; } // should look for a line before the ESSID acording to the scan line = outputLines[i - 1]; if (line.StartsWith("Encryption key:")) { network.IsEncrypted = line.Replace("Encryption key:", string.Empty).Trim() == "on"; break; } } if (result.Any(x => x.Name == network.Name) == false) { result.Add(network); } } } return(result.OrderBy(x => x.Name).ToList()); }
/// <summary> /// Retrieves current wireless connected network name. /// </summary> /// <returns>The connected network name.</returns> public string GetWirelessNetworkName() => ProcessRunner.GetProcessOutputAsync("iwgetid", "-r").Result;
/// <summary> /// Retrieves the network adapters. /// </summary> /// <returns>A list of network adapters.</returns> public List <NetworkAdapterInfo> RetrieveAdapters() { const string HWaddr = "HWaddr "; const string Ether = "ether "; var result = new List <NetworkAdapterInfo>(); var interfacesOutput = ProcessRunner.GetProcessOutputAsync("ifconfig").Result; var wlanOutput = ProcessRunner.GetProcessOutputAsync("iwconfig") .Result.Split('\n') .Where(x => x.Contains("no wireless extensions.") == false) .ToArray(); var outputLines = interfacesOutput.Split('\n').Where(x => string.IsNullOrWhiteSpace(x) == false).ToArray(); for (var i = 0; i < outputLines.Length; i++) { // grab the current line var line = outputLines[i]; // skip if the line is indented if (char.IsLetterOrDigit(line[0]) == false) { continue; } // Read the line as an adatper var adapter = new NetworkAdapterInfo { Name = line.Substring(0, line.IndexOf(' ')).TrimEnd(':') }; // Parse the MAC address in old version of ifconfig; it comes in the first line if (line.IndexOf(HWaddr) >= 0) { var startIndexHwd = line.IndexOf(HWaddr) + HWaddr.Length; adapter.MacAddress = line.Substring(startIndexHwd, 17).Trim(); } // Parse the info in lines other than the first for (var j = i + 1; j < outputLines.Length; j++) { // Get the contents of the indented line var indentedLine = outputLines[j]; // We have hit the next adapter info if (char.IsLetterOrDigit(indentedLine[0])) { i = j - 1; break; } // Parse the MAC address in new versions of ifconfig; it no longer comes in the first line if (indentedLine.IndexOf(Ether) >= 0 && string.IsNullOrWhiteSpace(adapter.MacAddress)) { var startIndexHwd = indentedLine.IndexOf(Ether) + Ether.Length; adapter.MacAddress = indentedLine.Substring(startIndexHwd, 17).Trim(); } // Parse the IPv4 Address { var addressText = ParseOutputTagFromLine(indentedLine, "inet addr:") ?? ParseOutputTagFromLine(indentedLine, "inet "); if (addressText != null) { if (IPAddress.TryParse(addressText, out var outValue)) { adapter.IPv4 = outValue; } } } // Parse the IPv6 Address { var addressText = ParseOutputTagFromLine(indentedLine, "inet6 addr:") ?? ParseOutputTagFromLine(indentedLine, "inet6 "); if (addressText != null) { if (IPAddress.TryParse(addressText, out var outValue)) { adapter.IPv6 = outValue; } } } // we have hit the end of the output in an indented line if (j >= outputLines.Length - 1) { i = outputLines.Length; } } // Retrieve the wireless LAN info var wlanInfo = wlanOutput.FirstOrDefault(x => x.StartsWith(adapter.Name)); if (wlanInfo != null) { adapter.IsWireless = true; var essidParts = wlanInfo.Split(new[] { EssidTag }, StringSplitOptions.RemoveEmptyEntries); if (essidParts.Length >= 2) { adapter.AccessPointName = essidParts[1].Replace("\"", string.Empty).Trim(); } } // Add the current adapter to the result result.Add(adapter); } return(result.OrderBy(x => x.Name).ToList()); }
public void WithInValidParams_ThrowsArgumentNullException() { Assert.ThrowsAsync <ArgumentNullException>(async() => await ProcessRunner.GetProcessOutputAsync(null)); }
/// <summary> /// Reboots this computer. /// </summary> public void Reboot() { #pragma warning disable 4014 ProcessRunner.GetProcessOutputAsync("reboot"); #pragma warning restore 4014 }
/// <summary> /// Retrieves the network adapters. /// </summary> /// <returns></returns> public List <NetworkAdapter> RetrieveAdapters() { var result = new List <NetworkAdapter>(); var interfacesOutput = ProcessRunner.GetProcessOutputAsync("ifconfig").Result; var wlanOutput = ProcessRunner.GetProcessOutputAsync("iwconfig") .Result.Split('\n') .Where(x => x.Contains("no wireless extensions.") == false) .ToArray(); var outputLines = interfacesOutput.Split('\n').Where(x => string.IsNullOrWhiteSpace(x) == false).ToArray(); for (var i = 0; i < outputLines.Length; i++) { var line = outputLines[i]; if (line[0] >= 'a' && line[0] <= 'z') { var adapter = new NetworkAdapter { Name = line.Substring(0, line.IndexOf(' ')) }; if (line.IndexOf(HWaddr) > 0) { var startIndexHwd = line.IndexOf(HWaddr) + HWaddr.Length; adapter.MacAddress = line.Substring(startIndexHwd).Trim(); } if (i + 1 >= outputLines.Length) { break; } // move next line line = outputLines[++i].Trim(); if (line.StartsWith("inet addr:")) { var tempIP = line.Replace("inet addr:", string.Empty).Trim(); tempIP = tempIP.Substring(0, tempIP.IndexOf(' ')); if (IPAddress.TryParse(tempIP, out var outValue)) { adapter.IPv4 = outValue; } if (i + 1 >= outputLines.Length) { break; } line = outputLines[++i].Trim(); } if (line.StartsWith("inet6 addr:")) { var tempIP = line.Replace("inet6 addr:", string.Empty).Trim(); tempIP = tempIP.Substring(0, tempIP.IndexOf('/')); if (IPAddress.TryParse(tempIP, out var outValue)) { adapter.IPv6 = outValue; } } var wlanInfo = wlanOutput.FirstOrDefault(x => x.StartsWith(adapter.Name)); if (wlanInfo != null) { adapter.IsWireless = true; var startIndex = wlanInfo.IndexOf(EssidTag) + EssidTag.Length; adapter.AccessPointName = wlanInfo.Substring(startIndex).Replace("\"", string.Empty); } result.Add(adapter); } } return(result.OrderBy(x => x.Name).ToList()); }
public async Task WithInvalidParams_ReturnsProcessError() { var data = await ProcessRunner.GetProcessOutputAsync("dotnet", "lol"); Assert.IsNotEmpty(data); }
/// <summary> /// Retrieves current wireless connected network name. /// </summary> /// <returns>The connected network name.</returns> public Task <string> GetWirelessNetworkName() => ProcessRunner.GetProcessOutputAsync("iwgetid", "-r");