Implement non-root Traceroute on Android--porting executable binaries script files with non-root permissions

Source: Internet
Author: User
Tags traceroute command

author : Wan Jing, the absolute dust

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


Sample code Download :

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

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


1. Principles and Ideas


file permission modification cannot be implemented : If 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 the file full path name command in the ADB push file name phone ;

[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 ADB uses the system user and 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 modify BusyBox permissions: System user does not have permission to modify 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

Application Solutions :

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

-- Copy the executable binaries to the installation directory : The cross-compiled busybox is placed in the res/assets/directory under the project directory;


2. Implementation Strategy


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

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

Modify file Permissions : Use the command to directly modify the permissions in the directory, note that this operation can be performed;

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

Get execution Results:


3. The API used to parse


(1) get the input stream of the assets directory file


InputStream is = Context.getassets (). open (source);
-- Get Assetsmanager: the Context.getassets () of the context object is called to get the Assetsmanager 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


gets the file size according to the input stream : invokes 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 : Invoke the Openfileoutput (absolute pathname, permission) of the context object to create an output stream of the file;

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) Executing binary files


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


get command-line results for execution:

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


4. Code Examples


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;/** can not understand the annotation I eat half a kilo of 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 executable file */varifyfile (Getapplicationcontext (), "BusyBox"); Break;case r.id.copy_traceroute:/* Copy traceroute executable 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:/* Execute editext command */cmd = Et_cmd.gettext (). ToString ();/* Execute 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, and if it does not exist, copy */private void Varifyfile (context context, String FileName) {try {* * * to see if the file exists, if not        The code in the exception will go */context.openfileinput (fileName);            } catch (FileNotFoundException Notfounde) {try {/* Copy file to the files directory of the app installation directory */copyfromassets (context, filename, filename);                /* Modify File Permissions script */String script = "chmod" + App_path + "/" + fileName;            /* Execute script */exe (script);            } catch (Exception e) {e.printstacktrace (); }}}/** copy the file from the assets directory to the files directory of the app installation directory */private void Copyfromassets (context context, String source,string de Stination) throws IOException {/* Gets the input stream of the file under the assets directory */inputstream is = Context.getassets (). open (source);/* Get file size */int s  ize = Is.available ();/* buffer to create file */byte[] buffer = new byte[size];/* read file into buffer */is.read (buffer);/* Close input stream */is.close ();/* Open the output stream of the app installation directory 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 ();}       /** Execute Shell script command */private list<string> exe (String cmd) {/* Gets the execution tool */process Process = null;/* Holds script execution results */ list<string> list = new arraylist<string> ();        try {/* Get runtime Environment */Runtime runtime = Runtime.getruntime ();             /* Execute 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 execution results 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= "Perform 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=" execution 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 execute" 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= "Execute" 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. Implementation results


Execute the BusyBox program :



Execute the traceroute program :



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



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.