public void ExecuteRemoteCommandTest( ) { Device device = GetFirstDevice ( ); BusyBox busyBox = new BusyBox(device); ConsoleOutputReceiver creciever = new ConsoleOutputReceiver ( ); Console.WriteLine ( "Executing 'busybox':" ); bool hasBB = false; try { device.ExecuteShellCommand ( "busybox", creciever ); hasBB = true; } catch ( FileNotFoundException ) { hasBB = false; } finally { Console.WriteLine ( "Busybox enabled: {0}", hasBB ); } Console.WriteLine ( "Executing 'busybox ls': " ); try { busyBox.ExecuteShellCommand ( "ls", creciever ); } catch ( Exception ex) { Console.WriteLine ( ex.Message ); throw; } }
public void ExecuteRemoteCommandTest() { Device device = GetFirstDevice(); ConsoleOutputReceiver creciever = new ConsoleOutputReceiver(); device.ExecuteShellCommand("pm list packages -f", creciever); Console.WriteLine("Executing 'ls':"); try { device.ExecuteShellCommand("ls -lF --color=never", creciever); } catch (UnknownOptionException) { device.ExecuteShellCommand("ls -l", creciever); } Console.WriteLine("Executing 'busybox':"); bool hasBB = false; try { device.ExecuteShellCommand("busybox", creciever); hasBB = true; } catch (FileNotFoundException) { hasBB = false; } finally { Console.WriteLine("Busybox enabled: {0}", hasBB); } Console.WriteLine("Executing 'unknowncommand':"); try { device.ExecuteShellCommand("unknowncommand", creciever); Assert.Fail(); } catch (FileNotFoundException) { // Expected exception } Console.WriteLine("Executing 'ls /system/foo'"); try { device.ExecuteShellCommand("ls /system/foo", creciever); Assert.Fail(); } catch (FileNotFoundException) { // Expected exception } }
private void CheckBox2_CheckedChanged(object sender, EventArgs e) { var receiver = new ConsoleOutputReceiver(); if (checkBox2.Checked) { AdbClient.Instance.ExecuteRemoteCommand("dumpsys battery set usb 1" + numericUpDown1.Value, Device, receiver); } else { AdbClient.Instance.ExecuteRemoteCommand("dumpsys battery set usb 0" + numericUpDown1.Value, Device, receiver); } MessageBox.Show(Device.Name + " says:\n \n" + receiver.ToString()); }
//a wrapper for the bulk of the shell command requirements private async void ShellCommand(string command) { try { var token = _cancelationToken.Token; var receiver = new ConsoleOutputReceiver(); //AdbClient.Instance.ExecuteRemoteCommand(command, Device, receiver); await AdbClient.Instance.ExecuteRemoteCommandAsync(command, Device, receiver, token, 10); } catch { Compiler.ExceptionListener.ThrowSilent(new ExceptionHandler(ExceptionType.DriverException, $"Command {command} was canceled and will not be retried.")); } }
public void EscapeLeaveWindow() { ConsoleOutputReceiver receiver = new ConsoleOutputReceiver(); var device = AdbClient.Instance.GetDevices().First(); AdbClient.Instance.ExecuteRemoteCommand("input keyevent KEYCODE_BACK", device, receiver); Thread.Sleep(1000); AdbClient.Instance.ExecuteRemoteCommand("input keyevent KEYCODE_BACK", device, receiver); Thread.Sleep(1000); if (Utils.CompareAt(device, "LeaveConfirm.png", new Rectangle(402, 769, 215, 52))) { AdbClient.Instance.ExecuteRemoteCommand("input keyevent KEYCODE_BACK", device, receiver); Thread.Sleep(1000); } }
public void TrowOnErrorTest() { AssertTrowsException <FileNotFoundException>("/dev/test: not found"); AssertTrowsException <FileNotFoundException>("No such file or directory"); AssertTrowsException <UnknownOptionException>("Unknown option -h"); AssertTrowsException <CommandAbortingException>("/dev/test: Aborting."); AssertTrowsException <FileNotFoundException>("/dev/test: applet not found"); AssertTrowsException <PermissionDeniedException>("/dev/test: permission denied"); AssertTrowsException <PermissionDeniedException>("/dev/test: access denied"); // Should not thrown an exception ConsoleOutputReceiver receiver = new ConsoleOutputReceiver(); receiver.ThrowOnError("Stay calm and watch cat movies."); }
private void CheckBox1_CheckedChanged(object sender, EventArgs e) { if (checkBox1.Checked) { var receiver = new ConsoleOutputReceiver(); AdbClient.Instance.ExecuteRemoteCommand("settings put system accelerometer_rotation 0", Device, receiver); MessageBox.Show(Device.Name + " says:\n \n" + receiver.ToString()); } else { var receiver = new ConsoleOutputReceiver(); AdbClient.Instance.ExecuteRemoteCommand("settings put system accelerometer_rotation 1", Device, receiver); MessageBox.Show(Device.Name + " says:\n \n" + receiver.ToString()); } }
/// <summary> /// Get the CpuUsage, MemoryUsage and the BatteryLevel periodically every 30 seconds and write them into the database --> Resources /// Also gets the five most expensive processes and their CPU/mem usage and writes them into the database --> ResIntens /// </summary> private void AccessWorkload() { while (!_token.IsCancellationRequested && AdbServer.GetConnectedDevices().Exists(x => x.Serial.Equals(_device.Serial))) { var receiver = new ConsoleOutputReceiver(); try { //Get the cpu usage and the five most expensive processes AdbServer.GetClient().ExecuteRemoteCommand(_cpuUsageCommand, _device, receiver); var cpu = GetCpuUsage(receiver.ToString()); var fiveProcesses = GetFiveProcesses(receiver.ToString()); var cpuFiveProcesses = GetCpuFiveProcesses(receiver.ToString()); var memFiveProcesses = GetMemFiveProcesses(receiver.ToString()); //Get the memusage AdbServer.GetClient().ExecuteRemoteCommand("cat /proc/meminfo", _device, receiver); var mem = GetMemUsage(receiver.ToString()); //Get the battery level AdbServer.GetClient().ExecuteRemoteCommand("dumpsys battery", _device, receiver); GetBatteryLevel(receiver.ToString()); var time = DateTime.Now; //Insert CPU/mem usage and the battery level into Resources _tableResources.InsertValues(_device.Serial, _device.Name, cpu, mem, _batteryLevel, time); //Insert the five most expensive processes into ResIntens for (var i = 0; i < 5; i++) { _tableResIntens.InsertValues(_device.Serial, _device.Name, Math.Round((double.Parse(cpuFiveProcesses[i].ToString(), CultureInfo.InvariantCulture) / _cpuTotal) * 100, 2), double.Parse(memFiveProcesses[i].ToString(), CultureInfo.InvariantCulture), fiveProcesses[i].ToString(), time); } //Invoke the DeviceWorkloadChanged event and wait 30 seconds AdbServer.CustomMonitor.Instance.OnDeviceWorkloadChanged(new DeviceDataEventArgs(_device)); } catch (Exception) { Console.WriteLine("Error while fetching data ... continuing"); } Thread.Sleep(Config.GetAccessWorkloadInterval()); } }
private async Task InstallPackage(DeviceData dd, string pkgname) { _logger.LogInformation($"Installing to {dd}"); var dev = mAdb.GetDevice(dd.Serial); var rcvr = new ConsoleOutputReceiver(); //Uninstall it firstly. await dev.Uninstall(pkgname, rcvr); //Install it now using var pkgstrm = mPkgMgr.GetStream(pkgname); await dev.Install(pkgstrm); _logger.LogInformation($"Installation finished on {dd}"); string activity = $"{pkgname}/.MainActivity"; await dev.StartActivity(activity); }
private static string SendToAdb(string command) { // Trying to send command to device via ADB try { device = AdbClient.Instance.GetDevices().First(); var receiver = new ConsoleOutputReceiver(); AdbClient.Instance.ExecuteRemoteCommand(command, device, receiver); return(receiver.ToString()); } // if can't => show error message and give a link to contact developer catch (Exception exception) { return(exception.ToString()); } }
public ZaloAdbRequest(Settings settings) { ConsoleOutputReceiver = new ConsoleOutputReceiver(); AdbPath = settings.AndroidDebugBridgeOsWorkingLocation; try { Adb = AndroidDebugBridge.CreateBridge(Path.Combine(settings.AndroidDebugBridgeOsWorkingLocation, "adb.exe"), true); Adb.Start(); } catch (Exception ex) { _log.Error(ex); } }
public void RestartApp() { ConsoleOutputReceiver receiver = new ConsoleOutputReceiver(); var device = AdbClient.Instance.GetDevices().First(); //force-stop tamquocchi app AdbClient.Instance.ExecuteRemoteCommand("am force-stop com.vgm.tqqat", device, receiver); Console.WriteLine("The device responded:"); Console.WriteLine(receiver.ToString()); System.Threading.Thread.Sleep(1000); AdbClient.Instance.ExecuteRemoteCommand("monkey -p com.vgm.tqqat -c android.intent.category.LAUNCHER 1", device, receiver); System.Threading.Thread.Sleep(10000); }
public async Task StopDesignerAsync(MobileDevice device) { var running = await IsDesignerRunning(device); if (!running) { return; } var data = GetDeviceData(device); var recv = new ConsoleOutputReceiver(); await AdbClient .Instance .ExecuteRemoteCommandAsync(DesignerStopCommand, data, recv, CancellationToken.None, LaunchTimeout); }
public void ExecuteRemoteCommandTest( ) { Device device = GetFirstDevice( ); ConsoleOutputReceiver creciever = new ConsoleOutputReceiver( ); device.ExecuteShellCommand("pm list packages -f", creciever); Console.WriteLine("Executing 'ls':"); try { device.ExecuteShellCommand("ls -lF --color=never", creciever); } catch (UnknownOptionException) { device.ExecuteShellCommand("ls -l", creciever); } Console.WriteLine("Executing 'busybox':"); bool hasBB = false; try { device.ExecuteShellCommand("busybox", creciever); hasBB = true; } catch (FileNotFoundException) { hasBB = false; } finally { Console.WriteLine("Busybox enabled: {0}", hasBB); } Console.WriteLine("Executing 'unknowncommand':"); try { device.ExecuteShellCommand("unknowncommand", creciever); Assert.Fail(); } catch (FileNotFoundException) { // Expected exception } Console.WriteLine("Executing 'ls /system/foo'"); try { device.ExecuteShellCommand("ls /system/foo", creciever); Assert.Fail(); } catch (FileNotFoundException) { // Expected exception } }
public void ShellCommand(string command) { if (data != null) { var receiver = new ConsoleOutputReceiver(); AdbClient.Instance.ExecuteRemoteCommand(command, data, receiver); //AppendText(richTextBox1, "ADB Log : Execute Command " + command + "/n", Color.Gold); if (!receiver.ToString().Equals("")) { //AppendText(richTextBox1, "ADB Log : Error Command " + receiver.ToString(), Color.Gold); } Console.WriteLine("The device responded:"); Console.WriteLine(receiver.ToString()); } }
public void SetAppPackage(string appPackage) { if (appPackage != "") { _appPackage = appPackage; Main.IO.Print($"App Package set to {appPackage}", ConsoleColor.DarkGreen); } else { string command = $"dumpsys window windows | grep -E 'mCurrentFocus'"; var receiver = new ConsoleOutputReceiver(); AdbClient.Instance.ExecuteRemoteCommand(command, Device, receiver); var echo = receiver.ToString(); _appPackage = echo; Main.IO.Print($"App Package set to the currently opened app.", ConsoleColor.DarkGreen); } }
public async Task <bool> LegacyCheckVersionInstalledAsync(MobileDevice device, int version) { var data = GetDeviceData(device); var recv = new ConsoleOutputReceiver(); await AdbClient .Instance .ExecuteRemoteCommandAsync(VersionCodeCommand, data, recv, CancellationToken.None, LaunchTimeout); var result = recv.ToString(); if (result.Contains($"versionCode={version}")) { return(true); } return(false); }
/// <summary> /// Check if pixel color at x, y is the same as pixelColor /// </summary> /// <param name="device">The device data object</param> /// <param name="x">x value screen coordinate</param> /// <param name="y">y value screen coordinate</param> /// <param name="pixelColor">The hex color value of the pixel</param> /// <returns></returns> public static bool CheckPixel(DeviceData device, ushort x, ushort y, String pixelColor) { var receiver = new ConsoleOutputReceiver(); uint offset = (uint)1280 * y + x; String command = $"cd /data; screencap screen.dump; dd if='screen.dump' bs=4 count=1 skip={offset} 2>/dev/null"; AdbClient.Instance.ExecuteRemoteCommand(command, device, receiver); string result = StringToHex(receiver.ToString()).Substring(0, 6); Console.WriteLine("Looking for " + pixelColor + ". Found " + result); if (result.Equals(pixelColor)) { return(true); } return(false); }
/// <summary> /// ADBコマンドを実行 /// </summary> /// <param name="command">コマンド列</param> /// <returns>コマンド出力文字列</returns> private String AdbShell(String command) { if (AndroidDevice.Value != null) { var receiver = new ConsoleOutputReceiver(); try { AdbClient.Instance.ExecuteRemoteCommand(command, AndroidDevice.Value, receiver); } catch (SharpAdbClient.Exceptions.AdbException e) { Debug.Print(e.ToString()); } return(receiver.ToString()); } return(""); }
public async Task <bool> CheckDesignerInstalledAsync(MobileDevice device) { var data = GetDeviceData(device); var recv = new ConsoleOutputReceiver(); await AdbClient .Instance .ExecuteRemoteCommandAsync(DesignerInstalledCommand, data, recv, CancellationToken.None, LaunchTimeout); var result = recv.ToString(); if (result.Contains($"package:{PackageName}")) { return(true); } return(false); }
private void button2_Click(object sender, EventArgs e) { screenshotNum++; var device = AdbClient.Instance.GetDevices().First(); var receiver = new ConsoleOutputReceiver(); AdbClient.Instance.ExecuteRemoteCommand("screencap -p /data/local/tmp/screenshot.png", device, receiver); using (SyncService service = new SyncService(new AdbSocket(new IPEndPoint(IPAddress.Loopback, AdbClient.AdbServerPort)), device)) using (Stream stream = File.OpenWrite(Path.GetTempPath() + "\\screenshot" + screenshotNum + ".png")) { service.Pull("/data/local/tmp/screenshot.png", stream, null, CancellationToken.None); stream.Dispose(); stream.Close(); } pictureBox1.Image = Image.FromFile(Path.GetTempPath() + "\\screenshot" + screenshotNum + ".png"); label5.Visible = true; label5.Text = "Saved screenshot " + '"' + "screenshot" + screenshotNum + ".png" + '"'; }
/// <summary> /// Install an apk to selected device from path /// </summary> public static void InstallAPK(string path) { if (!ScriptRun.Run) { return; } try { ConsoleOutputReceiver receiver = new ConsoleOutputReceiver(); AdbInstance.Instance.client.ExecuteRemoteCommand("adb install " + path, (Variables.Controlled_Device as DeviceData), receiver); } catch (InvalidOperationException) { } catch (ArgumentOutOfRangeException) { } }
public void Mining(int tried = 0) { if (tried > 5) { return; } ConsoleOutputReceiver receiver = new ConsoleOutputReceiver(); var device = AdbClient.Instance.GetDevices().First(); //if (Utils.CompareAt(device, "LeaveConfirm.png", new Rectangle(402, 769, 215, 52))) //{ // AdbClient.Instance.ExecuteRemoteCommand("input keyevent KEYCODE_BACK", device, receiver); // return; //} // 509 689 if (Utils.CompareAt(device, "stealButton.png", new Rectangle(509, 689, 55, 44))) { if (SelectMining()) { Mining(++tried); } return; } if (Utils.CompareAt(device, "SecondMining.png", new Rectangle(437, 749, 53, 41))) { AdbClient.Instance.ExecuteRemoteCommand("input tap 471 783", device, receiver); Thread.Sleep(2000); CreateTeam(); Console.WriteLine("Team Created!"); Thread.Sleep(1000); } else { if (SelectMining()) { Mining(++tried); } return; } }
public void ReadLogTest() { var device = new DeviceData() { Serial = "169.254.109.177:5555", State = DeviceState.Online }; var responses = new AdbResponse[] { AdbResponse.OK, AdbResponse.OK }; var responseMessages = new string[] { }; var requests = new string[] { "host:transport:169.254.109.177:5555", "shell:logcat -B -b system" }; var receiver = new ConsoleOutputReceiver(); using (Stream stream = File.OpenRead("logcat.bin")) using (ShellStream shellStream = new ShellStream(stream, false)) { Collection <Logs.LogEntry> logs = new Collection <LogEntry>(); Action <LogEntry> sink = (entry) => logs.Add(entry); this.RunTest( responses, responseMessages, requests, shellStream, () => { this.TestClient.RunLogServiceAsync(device, sink, CancellationToken.None, Logs.LogId.System).Wait(); }); Assert.Equal(3, logs.Count()); } }
private Point GetAdbScreenSize() { var receiver = new ConsoleOutputReceiver(); this.client.ExecuteRemoteCommand("wm size", device, receiver); log.Debug(receiver); //string[] strArr = receiver.ToString().Split(' ')[2].Split('x'); string[] strArr = new string[2] { "1920", "1200" }; log.Info(strArr); int[] intArr = Array.ConvertAll(strArr, Int32.Parse); log.Debug("done here..."); var endPoint = new Point(intArr[0], intArr[1]); log.Info("Độ phân giải màn hình giả lập bắt buộc phải sử dụng : " + endPoint.X + "x" + endPoint.Y); return(endPoint); }
void EchoTest(string s, string command) { var device = GetByName(s); if (device != null) { var receiver = new ConsoleOutputReceiver(); AdbClient.Instance.ExecuteRemoteCommand(command, device, receiver); AppendText(richTextBox1, "ADB Log : Execute Command " + command + "/n", Color.Gold); if (!receiver.ToString().Equals("")) { AppendText(richTextBox1, "ADB Log : Error Command " + receiver.ToString(), Color.Gold); } Console.WriteLine("The device responded:"); Console.WriteLine(receiver.ToString()); } }
private void AssertTrowsException <T>(string line) where T : Exception { ConsoleOutputReceiver receiver = new ConsoleOutputReceiver(); try { receiver.ThrowOnError(line); throw new AssertFailedException($"An exception of type {typeof(T).FullName} was not thrown"); } catch (T) { // All OK - an exception of type T was thrown } catch (Exception ex) { throw new AssertFailedException($"An exception of type {typeof(T).FullName} was expected, but of type {ex.GetType().FullName} was thrown instead."); } }
public void ReadLogTest() { var device = new DeviceData() { Serial = "169.254.109.177:5555", State = DeviceState.Online }; var responses = new AdbResponse[] { AdbResponse.OK, AdbResponse.OK }; var responseMessages = new string[] { }; var requests = new string[] { "host:transport:169.254.109.177:5555", "shell:logcat -B -b system" }; var receiver = new ConsoleOutputReceiver(); using (Stream stream = File.OpenRead("logcat.bin")) using (ShellStream shellStream = new ShellStream(stream, false)) { Logs.LogEntry[] logs = null; this.RunTest( responses, responseMessages, requests, shellStream, () => { logs = AdbClient.Instance.RunLogService(device, Logs.LogId.System).ToArray(); }); Assert.AreEqual(3, logs.Count()); } }
private TcpClient startConnection() { Debug.Log("starting socket"); tcpServer = new TcpListener(IPAddress.Parse(serverIP), hostPort); Debug.Log("waiting for device connection"); tcpServer.Start(); var acceptClientTask = tcpServer.AcceptTcpClientAsync(); Debug.Log("starting android connection"); //https://github.com/quamotion/madb var adbServer = new AdbServer(); adbServer.StartServer(adbPath, true); adbClient = new AdbClient(); var devices = adbClient.GetDevices(); if (devices.Count == 0) { Debug.LogError("Error: Device not connected"); return(null); } device = devices.Last(); string command1 = @"am force-stop com.example.mediapipemultihandstrackingapp"; var receiver1 = new ConsoleOutputReceiver(); adbClient.ExecuteRemoteCommand(command1, device, receiver1); Debug.Log("Stop remote app result: " + receiver1.ToString()); Debug.Log("Resetting reverse connection"); adbClient.RemoveAllReverseForwards(device); var reverseResult = adbClient.CreateReverseForward( device, "tcp:" + devicePort.ToString(), "tcp:" + hostPort.ToString(), true); string command2 = @"monkey -p com.example.mediapipemultihandstrackingapp -c android.intent.category.LAUNCHER 1"; var receiver2 = new ConsoleOutputReceiver(); adbClient.ExecuteRemoteCommand(command2, device, receiver2); Debug.Log("Start remote app result: " + receiver2.ToString()); return(acceptClientTask.Result); }
/// <summary> /// Check if screenrecord function is available -> Huawei does not have this function anymore /// </summary> /// <param name="device">Check if this device has function screenrecord function</param> /// <returns>TRUE if usable, FALSE if not usable</returns> public static bool ScrRecAvailable(DeviceData device) { //create receiver var receiver = new ConsoleOutputReceiver(); //execute command and read input AdbServer.GetClient().ExecuteRemoteCommand("ls /system/bin/", device, receiver); //convert input to string var received = receiver.ToString(); //check if screenrecord is listed var usable = received.Contains("screenrecord"); Console.WriteLine("Screenrecord function usable: " + usable); //return if screenrecord is usable or not return(usable); }
private void AppsList_button_Click(object sender, EventArgs e) { var device = AdbClient.Instance.GetDevices().First(); var receiver = new ConsoleOutputReceiver(); AdbClient.Instance.ExecuteRemoteCommand("ls -x1 /sdcard/Android/data", device, receiver); txtLogBox.Text = "Ocultadas apps en el comboBox que puedan proceder de android(sistema), samsung o google para evitar borrados por error. En el Log se pueden ver todas las apps sin filtrar\r\n-----------\r\nHidden apps in the comboBox that can come from android(system), samsung or google to avoid being deleted by mistake. In the Log you can see all the unfiltered apps\r\n-----------\r\n"; txtLogBox.Text = txtLogBox.Text + receiver; string temp = receiver.ToString().Replace("\r\n", "-"); Char delimiter = '-'; String[] listaApps = temp.Split(delimiter); appsList.Items.Clear(); var res = listaApps.Where(s => !listaAppsProtected.Any(ignored => s.Contains(ignored))).ToList(); foreach (var item in res) { appsList.Items.Add(item); } }
static List <ProcInfo> GetProcs(AdbClient client, DeviceData device) { ConsoleOutputReceiver consoleOutput = new ConsoleOutputReceiver(); client.ExecuteRemoteCommand("ps", device, consoleOutput); string[] lines = consoleOutput.ToString().Split("\r\n"); if (lines.Length < 10) { // some devices require -A consoleOutput = new ConsoleOutputReceiver(); client.ExecuteRemoteCommand("ps -A", device, consoleOutput); lines = consoleOutput.ToString().Split("\r\n"); } //root 1 0 20264 2896 0 0 S init //USER PID PPID VSZ RSS WCHAN ADDR S NAME List <ProcInfo> procs = new List <ProcInfo>(); string[] headers = lines[0].Split(' ').Where(n => n != "").ToArray(); for (int c = 1; c < lines.Length; c++) { string[] parts = lines[c].Split(' ').Where(n => n != "").ToArray(); if (parts.Length > 0) { if (parts[0] != "system" && parts[0] != "root") { ProcInfo proc = new ProcInfo { User = parts[0], Pid = int.Parse(parts[1]), Name = parts[8], }; procs.Add(proc); } } } return(procs); }
public void ExecuteRemoteRootCommandTest( ) { Device device = GetFirstDevice ( ); ConsoleOutputReceiver creciever = new ConsoleOutputReceiver ( ); Console.WriteLine ( "Executing 'ls':" ); if ( device.CanSU ( ) ) { try { device.ExecuteRootShellCommand ( "busybox ls -lFa --color=never", creciever ); } catch ( UnknownOptionException ) { device.ExecuteRootShellCommand ( "ls -lF", creciever ); } } else { // if the device doesn't have root, then we check that it is throwing the PermissionDeniedException try { try { device.ExecuteRootShellCommand ( "busybox ls -lFa --color=never", creciever ); } catch ( UnknownOptionException ) { device.ExecuteRootShellCommand ( "ls -lF", creciever ); } Assert.Fail(); } catch (PermissionDeniedException) { // Expected exception } } }
/// <summary> /// Lists all processes running on the device. /// </summary> /// <param name="device"> /// The device on which to list the processes that are running. /// </param> /// <returns> /// An <see cref="IEnumerable{AndroidProcess}"/> that will iterate over all /// processes that are currently running on the device. /// </returns> public static IEnumerable<AndroidProcess> ListProcesses(this DeviceData device) { // There are a couple of gotcha's when listing processes on an Android device. // One way would be to run ps and parse the output. However, the output of // ps differents from Android version to Android version, is not delimited, nor // entirely fixed length, and some of the fields can be empty, so it's almost impossible // to parse correctly. // // The alternative is to directly read the values in /proc/[pid], pretty much like ps // does (see https://android.googlesource.com/platform/system/core/+/master/toolbox/ps.c). // // The easiest way to do the directory listings would be to use the SyncService; unfortunately, // the sync service doesn't work very well with /proc/ so we're back to using ls and taking it // from there. List<AndroidProcess> processes = new List<AndroidProcess>(); // List all processes by doing ls /proc/. // All subfolders which are completely numeric are PIDs ConsoleOutputReceiver receiver = new ConsoleOutputReceiver(); device.ExecuteShellCommand("/system/bin/ls /proc/", receiver); Collection<int> pids = new Collection<int>(); using (StringReader reader = new StringReader(receiver.ToString())) { while (reader.Peek() > 0) { string line = reader.ReadLine(); if (!line.All(c => char.IsDigit(c))) { continue; } var pid = int.Parse(line); pids.Add(pid); } } // For each pid, we can get /proc/[pid]/stat, which contains the process information in a well-defined // format - see http://man7.org/linux/man-pages/man5/proc.5.html. // Doing cat on each file one by one takes too much time. Doing cat on all of them at the same time doesn't work // either, because the command line would be too long. // So we do it 50 processes at at time. StringBuilder catBuilder = new StringBuilder(); ProcessOutputReceiver processOutputReceiver = new ProcessOutputReceiver(); for (int i = 0; i < pids.Count; i++) { if (i % 50 == 0) { catBuilder.Clear(); catBuilder.Append("cat "); } catBuilder.Append($"/proc/{pids[i]}/stat "); if (i > 0 && (i % 50 == 0 || i == pids.Count - 1)) { device.ExecuteShellCommand(catBuilder.ToString(), processOutputReceiver); } } processOutputReceiver.Flush(); return processOutputReceiver.Processes; }
public void ExecuteRemoteCommandUnresponsiveTest() { var device = new DeviceData() { Serial = "169.254.109.177:5555", State = DeviceState.Online }; var responses = new AdbResponse[] { AdbResponse.OK, AdbResponse.OK }; var responseMessages = new string[] { }; var requests = new string[] { "host:transport:169.254.109.177:5555", "shell:echo Hello, World" }; var receiver = new ConsoleOutputReceiver(); this.RunTest( responses, responseMessages, requests, null, () => { AdbClient.Instance.ExecuteRemoteCommand("echo Hello, World", device, receiver); }); }
public void ExecuteRemoteCommandTest() { var device = new DeviceData() { Serial = "169.254.109.177:5555", State = DeviceState.Online }; var responses = new AdbResponse[] { AdbResponse.OK, AdbResponse.OK }; var responseMessages = new string[] { }; var requests = new string[] { "host:transport:169.254.109.177:5555", "shell:echo Hello, World" }; byte[] streamData = Encoding.ASCII.GetBytes("Hello, World\r\n"); MemoryStream shellStream = new MemoryStream(streamData); var receiver = new ConsoleOutputReceiver(); this.RunTest( responses, responseMessages, requests, shellStream, () => { AdbClient.Instance.ExecuteRemoteCommand("echo Hello, World", device, receiver); }); Assert.AreEqual("Hello, World\r\n", receiver.ToString()); }