Implement non-root Traceroute on Android---Non-root permission to run binary file script files

Source: Internet
Author: User
Tags run traceroute traceroute command

author : Wan Jing, the absolute dust

Reprint Please famous source : http://blog.csdn.net/shulianghan/article/details/36438365


Demo Sample code download :

-- CSDN : http://download.csdn.net/detail/han1202012/7639253;

-- GitHub : https://github.com/han1202012/TracerouteAndBusybox;


1. Principles and Ideas


file permission changes cannot be implemented : Suppose No root privileges , you cannot change the file permissions of a binary file;

-- push BusyBox to Android : use adb push command to pass BusyBox to SD card, note that uploading to memory is not possible;

-- upload to SD card success : Use adb push file name in the file full path name command;

[Email protected]:~/csdn$ adb push busybox-armv7l/sdcard/octopus/busybox3256 kb/s (1109128 bytes in 0.332s)
-- failed to upload to memory: Failed to upload to memory using ADB push, because the ADB is using the system user, only the root user has permission to write data to memory;

[Email protected]:~/csdn$ adb push busybox-armv7l/data/busyboxfailed to copy ' busybox-armv7l ' to '/data/busybox ': Permis Sion denied
-- failed to view and change BusyBox permissions: The system user does not have permission to change the SD card file mode;

[Email Protected]:/sdcard/octopus $ ll-rw-rw-r--root     sdcard_rw  1109128 2014-07-08 19:49 busybox[email Protected]:/sdcard/octopus $ chmod 755 busybox                              Unable to chmod busybox:operation not permitted

How to resolve the application :

-- application-specific user : The Android operating system will set a user for each application, and the user has full access to the files under its installation folder (/data/data//);

-- Copy the executable binaries to the installation folder : Place the cross-compiled busybox under the res/assets/folder under the project folder;


2. Implementation Strategy


File Initial placement : The cross-compiled BusyBox file is placed under the/res/assets/folder in the project folder;

file copy : Copy the binary file to the Files folder of the app's installation folder, i.e. under the/data/data/package name/files/;

Change file Permissions : Use the command can directly change the permissions under the folder, note that this operation is able to run;

Run BusyBox : Run in code./data/data/Package Name/files/busybox;

Get run Result:


3. The API used to parse


(1) get the input stream of the Assets folder file


InputStream is = Context.getassets (). open (source);
-- Get Assetsmanager: The Assetsmanager object can be obtained by invoking the Context.getassets () of the context object;

-- Get input stream : Call Assetsmanager's Open (String fileName) to get the input stream of the corresponding file name;


(2) file stream related operations


get file size according to input stream : Call the Inputstream.available () method of the input stream;

int size = is.available ();

to read a file into a buffer: Creates a byte array buffer that is the same size as the file, and the input stream stores the data in the buffer;

byte[] buffer = new Byte[size];is.read (buffer); Is.close ();

write the file into memory : Call the Context object's Openfileoutput (absolute path name, permissions), you can create a file output stream;

FileOutputStream output = context.openfileoutput (destination, context.mode_private); output.write (buffer); O Utput.close ();



(3) Get the absolute path to the file


get the App absolute installation path : Call the Context object's Getfilesdir (). GetAbsolutePath () method;

String Filespath = Context.getfilesdir (). GetAbsolutePath ();


(4) Run binary files


Create a Process object and use the process to run the shell script command :


get Run command-line results:

            InputStream is = Process.getinputstream ();            BufferedReader br = new BufferedReader (new InputStreamReader (IS));            String line = null;              while (line = Br.readline ())! = null) {                  processlist.add (line);             }            


4. Sample Code Demo


mainactivity Main program code :

Package Cn.org.octopus.tracerouteandbusybox;import Java.io.bufferedreader;import java.io.FileNotFoundException; Import Java.io.fileoutputstream;import Java.io.ioexception;import Java.io.inputstream;import Java.io.inputstreamreader;import Java.util.arraylist;import Java.util.list;import Android.content.Context;import Android.os.bundle;import Android.support.v7.app.actionbaractivity;import Android.view.view;import Android.widget.edittext;import android.widget.textview;/** don't understand stare I eat half catty dog food:-) */public class Mainactivity extends actionbaractivity {private EditText et_cmd;private String app_path;private TextView tv_result; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.home_activity); * Initialize Control */et_cmd = (EditText) Findviewbyid (r.id.et_cmd); tv_result = (TextView) Findviewbyid (R.id.tv_result);/* Get the app installation path */app_path = Getapplicationcontext (). Getfilesdir (). GetAbsolutePath (); /** button click event */public void OnClick (view view) {int ID = view.getid (); switch (ID) {case r.id.copy_busybox:/* Copy busybox can run file */varifyfile (Getapplicationcontext (), "BusyBox" ); break;case r.id.copy_traceroute:/* copy traceroute can run file */varifyfile (Getapplicationcontext (), "traceroute"); Case r.id.exe_busybox:/* adds the BusyBox command to editext */string cmd = "." + App_path + "/busybox"; System.out.println (Et_cmd); Et_cmd.settext (cmd); break;case r.id.exe_traceroute:/* add traceroute command to Editext */cmd = " . "+ App_path +"/traceroute 8.8.8.8 "; et_cmd.settext (cmd); Break;case r.id.exe:/* Run editext command */cmd = Et_cmd.gettext (). ToString ();/* Run script command */list<string> results = exe (CMD); string result = "";/* Convert the results to a string, output to TextView */for (string line:results) {result + = line + "\ n";} Tv_result.settext (result); break;default:break;}} /** Verify that the file exists, assuming that it does not exist, copy */private void Varifyfile (context context, String FileName) {try {* * * to see if the file exists, assuming no        The code in the exception will go */context.openfileinput (fileName);        } catch (FileNotFoundException Notfounde) {    try {/* Copy the file to the Files folder of the app installation folder */copyfromassets (context, filename, filename);                /* Change file Permissions script */String script = "chmod" + App_path + "/" + fileName;            /* Run the script */exe (script);            } catch (Exception e) {e.printstacktrace ();  }}}/** copy the file from the assets folder to the Files folder in the app installation folder */private void Copyfromassets (context context, String source,string Destination) throws IOException {/* Gets the input stream of the file under the assets folder */inputstream is = Context.getassets (). open (source);/* Get file size */i NT size = is.available ();/* buffer to create file */byte[] buffer = new byte[size];/* reads the file into the buffer */is.read (buffer);/* Closes the input stream */is.close ( /*/* Open the output stream of the app installation folder file */fileoutputstream output = Context.openfileoutput (destination,context.mode_private);/* Writes the file out of the buffer to the in-memory */output.write (buffer);/* Closes the output stream */output.close ();} /** run Shell script command */private list<string> exe (String cmd) {/* Get run tool */process Process = NULL;/* Store script run knotFruit */list<string> List = new arraylist<string> ();        try {/* Get runtime Environment */Runtime runtime = Runtime.getruntime ();             /* Run the script */process = runtime.exec (cmd);            /* Get input stream for script results */InputStream is = Process.getinputstream ();            BufferedReader br = new BufferedReader (new InputStreamReader (IS));              String line = null;             /* Read the script run result line by row */while (lines = Br.readline ()) = null) {List.add);         } br.close ();          } catch (IOException e) {e.printstacktrace (); } return list;}}


home_activity.xml Layout file code :

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Match_parent "android:layout_height=" match_parent "android:orientation=" vertical " > <linearlayout android:layout_width= "match_parent" android:layout_height= "Wrap_content" and roid:gravity= "center" android:orientation= "Horizontal" > <button android:id= "@+id/copy_busy Box "android:layout_width=" Wrap_content "android:layout_height=" Wrap_content "Android:onc lick= "OnClick" android:text= "copy BusyBox" android:textsize= "7DP" android:textstyle= "bold"/            > <button android:id= "@+id/copy_traceroute" android:layout_width= "Wrap_content"            android:layout_height= "Wrap_content" android:onclick= "OnClick" android:text= "Copy traceroute"       Android:textsize= "7DP"     android:textstyle= "Bold"/> <button android:id= "@+id/exe_busybox" Android:layout_w Idth= "Wrap_content" android:layout_height= "wrap_content" android:onclick= "OnClick" Androi            d:text= "Run BusyBox" android:textsize= "7DP" android:textstyle= "bold"/> <button Android:id= "@+id/exe_traceroute" android:layout_width= "wrap_content" android:layout_height= "Wrap_c            Ontent "android:onclick=" OnClick "android:text=" Run Traceroute "android:textsize=" 7DP " android:textstyle= "Bold"/> </LinearLayout> <linearlayout android:layout_width= "Match_pare            NT "android:layout_height=" wrap_content "android:orientation=" Horizontal "> <edittext            Android:id= "@+id/et_cmd" android:layout_width= "0DP" android:layout_height= "Wrap_content" android:layout_weight="4" android:hint= "Enter the command to run" android:textstyle= "bold"/> <button android:id= " @+id/exe "android:layout_width=" 0DP "android:layout_height=" Wrap_content "Android:layout_            weight= "1" android:onclick= "OnClick" android:text= "Run" android:textsize= "10DP" android:textstyle= "Bold"/> </LinearLayout> <textview android:id= "@+id/tv_result" Android : layout_width= "match_parent" android:layout_height= "match_parent" android:background= "#000000" Androi D:textcolor= "#FFF" android:textsize= "10DP" android:textstyle= "bold"/></linearlayout>


5. Running Results


To run the BusyBox program :



To run the traceroute program :



Demo Sample code download :

-- CSDN : http://download.csdn.net/detail/han1202012/7639253;

-- GitHub : https://github.com/han1202012/TracerouteAndBusybox;



author : Wan Jing, the absolute dust

Reprint Please famous source : http://blog.csdn.net/shulianghan/article/details/36438365



Implement non-root Traceroute on Android---Non-root permission to run binary file script files

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.