I'm trying to run a shell command in my Android app in order to check if a give tcp port is opened or not:
Runtime.getRuntime().exec(arrayOf("/system/bin/sh", "-c", "netstat -tulpn | grep :8080"))
Running this command in Android version < 10, works fine. It will do a full scan and return the entry if there is the given port used.
But in Android 10, it is not working anymore. The process exec will return:
Process[pid=9534 ,hasExited=true, exitcode=1]
When reading the inputStream of the process it is always null, while executing netstat -tulpn | grep :8080 from terminal will return an entry, as expected.
Running
Runtime.getRuntime().exec(arrayOf("/system/bin/sh", "-c", "netstat -tulpn"))
alone, and parsing the output, will only show:
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program Name
and no other data at all.
I only have this problem in Android 10, because for older versions it is working.
Has anything changed in Android 10 regarding to shell commands? It is necessary for me to run this command.
Any help would be appreciated...
This is most likely because of privacy protection improved in Android 10.
Look here: https://developer.android.com/about/versions/10/privacy/changes#proc-net-filesystem
My goal was to check if a given tcp port was in use or not. I made this method that did the job that I was looking for:
private fun isPortUsed(port: Int): Boolean {
return try {
// Try to open socket at the given port
val socket = ServerSocket(port)
// Release port
socket.close()
false
} catch (ex: BindException) {
// Port is already in use
true
} catch (ex: Exception) {
// Other reason for failing
false
}
}
Related
I've tried connecting to an API running locally on my machine to retrieve values in an Android emulator.
I keep getting 404 Error. Any idea what should be done here for the API? Thank you for your help.
var test = "";
var url = "http://10.0.2.2:60002/api/values/" + Convert.ToInt32(Id);
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
$"{user}:{pass}")));
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
var response = await client.GetStringAsync(url);
test = response;
}
return test;
use 127.0.0.1 as the ip address. It should solve the problem.
If not,
type "adb shell ifconfig" or "adb shell ipaddr" in your command prompt.
(once of them should work)
Check if your either one of your machine's ip adresses are there. If there is a matching one use it.
To check your machine's ipaddress,
If you are using windows
Type ipconfig in your command prompt.
If you are using Linux
Type ifconfig in your shell.
I try to enable/disable wifi programmatically within my Xamarin Ui Test.
I already found this: Android: How to Enable/Disable Wifi or Internet Connection Programmatically. But it seems not to work within the UiTest.
I also tried something like this:
Context appContext = Android.App.Application.Context;
var wifiManager = (WifiManager)appContext.GetSystemService(Context.WifiService);
bool status = false;
wifiManager.SetWifiEnabled(status);
The first line (Android.App.Application.Context) throws an exception:
Message: System.IO.FileNotFoundException : Could not load file or assembly 'Java.Interop, Version=0.1.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065' or one of its dependencies. The system cannot find the file specified.
I'm using following namespaces:
using Android.Net.Wifi;
using Android.Content;
My project has a reference to Mono.Android.
The backdoor approach works fine for me.
The solution that works for me was a combination of:
Android: How to Enable/Disable Wifi or Internet Connection Programmatically
https://learn.microsoft.com/en-us/appcenter/test-cloud/uitest/working-with-backdoors
Some small own changes (for appcontext/context). Just context did not work for me.
1.: Add following line to the AndroidManifest.xml file of the Android project:
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
2.: Add following lines to the MainActivity.cs of the Android project:
using Java.Interop;
using Android.Net.Wifi;
[Export("ChangeWifiState")]
public void ChangeWifiState(bool state)
{
Context appContext = Android.App.Application.Context;
var wifiManager = (WifiManager)appContext.GetSystemService(WifiService);
wifiManager.SetWifiEnabled(state);
}
3.: Call following method out of the Xamarin Ui Test:
app.Invoke("ChangeWifiState", false); // true to enable wifi, false to disable wifi
PS: I use Xamarin Forms. I've got four different projects: a core project, an Android project, a Ui project, and a test project.
I just found a second solution without using the actual app.
It uses ADB commands to enable/disable wifi:
var process = new System.Diagnostics.Process();
var startInfo = new System.Diagnostics.ProcessStartInfo
{
WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
FileName = "cmd.exe",
Arguments = "/C adb shell am start -a android.intent.action.MAIN -n com.android.settings/.wifi.WifiSettings adb shell input keyevent 19 & adb shell input keyevent 19 & adb shell input keyevent 23 & adb shell input keyevent 82 & adb shell input tap 500 1000"
};
process.StartInfo = startInfo;
process.Start();
This can be used without a rooted device :).
Steps explained:
adb shell am start -a android.intent.action.MAIN -n com.android.settings/.wifi.WifiSettings opens the wifi settings.
adb shell input keyevent 23 enables/disables wifi.
I'm not sure why the command adb shell input keyevent 19 is used, but it works.
adb shell input keyevent 82 clicks the menu button to change back to the original app.
adb shell input tap 500 1000 clicks the coordinate x=500, y=1000 (center of screen).This may need be changed for different solutions.
Sources for this solution:
How to turn off Wifi via ADB?
ADB Shell Input Events
Run Command Prompt Commands
I have an Android application utilizing RootTools v4.2 (the latest I know of) and I have followed their documentation on how to execute shell commands as root. Sometimes the commands execute just fine, other times the app crashes with the following exception.
java.lang.IllegalStateException: Unable to add commands to a closed shell
Here is the actual code the exception is being throw on:
RootTools.getShell(true).add(cmd);
So I'm wondering since the docs make no mention of this sort of problem if there is something else I'm doing wrong? Looking through the docs I see nothing on how to ensure I get an open shell before I start adding commands.
This code is working with me . Try to install the Library again may be its not vaild .
if(RootTools.isAccessGiven()){
try {
Shell shell = RootTools.getShell(true);
JavaCommand cmd = new JavaCommand(0,this,"input keyevent 26");
shell.add(cmd);
}
catch (Exception e){
Log.d("ERRORS : ",e.getMessage());
}
}
Can anyone say, whether adb commands can be executed through my android application. If it is possible to execute, how it can be implemented?
You can do it with this:
Process process = Runtime.getRuntime().exec("your command");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
Don't forget to surround it with a try and catch statement.
Edit:
#Phix is right, ProcessBuilder would be better to use.
Normal Android apps have different privileges to processes started via adb, e.g., processes started via adb are allowed to the capture the screen whereas normal apps aren't. So, you can execute commands from your app via Runtime.getRuntime().exec(), but they won't have the same privileges as if you had executed from an adb shell.
i came across this post looking for a different query, but i have worked specifically with input on android before, so I'd just like to put some clarity on the matter.
The reason why
Runtime.getRuntime().exec("adb shell input keyevent 120");
Is not working, is because you are not removing
adb shell
The ADB part is only for use on your computer, if you have incorrectly installed ADB, the command would actually be a path to the adb.exe file on your computer, like this
C:\XXXX\ADB Files\adb.exe shell
or
C:\XXXX\ADB Files\adb shell
The shell part tells the ADB program on your computer to access the devices shell, so your device will not know what shell is either...
Using sh /path/to/commandList.sh will execute the commads listed in commandList.sh as it is a shell script (a .batch file on windows is similar )
The command you want to use is
Runtime.getRuntime().exec("input keyevent 120");
However this will cause Environment null and working directory null, you can bypass this by writing the commands to a shell script ( .sh file ) and then running the script with
Runtime.getRuntime().exec("sh path/to/shellScript.sh");
Sometimes the sh is not needed, but i use it just incase.
I hope this clears at least something up :)
adb shell invoked in Runtime.getRuntime().exec is not running under shell user. It provide shell but with same process owner user (like u0_a44). That's the reason all command did not work.
This is what I do in Kotlin, I also get command responses too
fun runShellCommand(command: String) {
// Run the command
val process = Runtime.getRuntime().exec(command)
val bufferedReader = BufferedReader(
InputStreamReader(process.inputStream)
)
// Grab the results
val log = StringBuilder()
var line: String?
line = bufferedReader.readLine()
while (line != null) {
log.append(line + "\n")
line = bufferedReader.readLine()
}
val Reader = BufferedReader(
InputStreamReader(process.errorStream)
)
// if we had an error during ex we get here
val error_log = StringBuilder()
var error_line: String?
error_line = Reader.readLine()
while (error_line != null) {
error_log.append(error_line + "\n")
error_line = Reader.readLine()
}
if (error_log.toString() != "")
Log.info("ADB_COMMAND", "command : $command $log error $error_log")
else
Log.info("ADB_COMMAND", "command : $command $log")
}
Executing
Runtime.getRuntime().exec("adb shell input keyevent 120");
I got the following error:
java.io.IOException: Cannot run program "adb": error=13, Permission denied.
Executing
Runtime.getRuntime().exec("adb shell input keyevent 120");
There is no error but at the same time, my request is not processed to take the screenshot.
I found out this was working in earlier versions of android but later it was removed. Though I'm not able to provide the source here why it is not working.
Hope this helps someone like me who is trying to use this approach to take the screenshot when the app is not in the foreground.
Process process = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(process.getOutputStream());
string cmd = "/system/bin/input keyevent 23\n";
os.writeBytes(cmd);
the phone must be rooted. here I have executed adb command "input keyevent 23".
remember when you execute adb command through su you does not need to add "adb shell input keyevent 23"
On some Android devices, in the ADB shell, I can only run echo, cd, ls. When I run:
tar -cvf //mnt/sdcard/BackUp1669/apk/test.tar /mnt/sdcard/test.apk
Or the command cp, it returns:
sh: tar: not found
Why can I not run these commands? Some devices support these commands. My end goal is to copy a file from the /data/data folder to SD card. I got su and I got the following code:
int timeout = 1000;
String command = "tar -cvf /" + Environment.getExternalStorageDirectory() + "/cp/"
+ packageName + ".tar" + " " + path;
DataOutputStream os = new DataOutputStream(process.getOutputStream());
BufferedReader is = new BufferedReader(new InputStreamReader(new DataInputStream(
process.getInputStream())), 64);
String inLine;
try {
StringBuilder sbCommand = new StringBuilder();
sbCommand.append(command).append(" ");
sbCommand.append("\n");
os.writeBytes(command.toString());
if (is != null) {
for (int i = 0; i < timeout; i++) {
if (is.ready())
break;
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (is.ready()) {
inLine = is.readLine();
} else {
}
}
} catch (IOException e) {
e.printStackTrace();
}
It always stops in is.ready(), and when I changed it to process.waitfor() it also stopped. Why?
As far as i know, the only way to run shell commands is:
Process proc = Runtime.getRuntime().exec("your command");
You can run Linux commands on Android. But there are usually just very few pre-installed.
If you want to add more commands you might want to root your device and install busybox on it.
This is not for productive use within an application but can help you to work with your device.
If you have the binaries for your system, you can run anything on your system.
Saying that you have to understand that you have to find the binaries for tar.
Look here http://forum.xda-developers.com/showthread.php?t=872438
And possibly other places..
You can probably get this done by using a Terminal Emulator app. As you wrote above, I don't know how well DOS commands will work. But, a Terminal Emulator works without root.
You can install Termux app on your android device and run Linux command by using that app
Install busybox, then type the command in the following format:
busybox [linux command]
You cannot use all the linux commands without busybox, because Android doesn't have all the binaries that are available in a standard linux operating system.
FYI, a binary is just a file that contains compiled code. A lot of the default binaries are stored in /system/bin/sh directory. All these commands like 'cp' 'ls' 'get' etc, are actually binaries. You can view them through:
ls -a /system/bin/sh
Hope this helps.
In reply to Igor Ganapolsky, You would have to have a database set up for locate.
Probably find would be adequate for your needs.
example:
find -name *.apk