2022-05-27 Android Android getRuntime()、exec 执行命令(linux 下的bin文件等)并解得到返回值、执行ping命令

一、形式一:只执行命令不获取返回值。

    public static String execute_command(String cmd) {
        try {
            //String keyCommand = "setprop " + propName;
            Runtime runtime = Runtime.getRuntime();
            Process proc = runtime.exec(cmd);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  cmd;
    }

二、形式二:执行命令并且获取返回值。

   private String playRunTime(String cmd) throws Exception
   {
       //  String cmd = "adb version";
         String ret = null;
         Process p = Runtime.getRuntime().exec(cmd);
         InputStream is = p.getInputStream();
         BufferedReader reader = new BufferedReader(new InputStreamReader(is));
         String line; while ((line = reader.readLine()) != null)
         {
           //tv_result.append(line + "");
             ret = line;
             System.out.println(TAG+"  "+line);
         }
         p.waitFor();
         is.close();
         reader.close();
         p.destroy();
         return ret;
   }

三、执行ping的需要下面的形式

    public  boolean execCommand(String cmd){
        Process process = null;
        DataOutputStream os = null;
        try{
            process = Runtime.getRuntime().exec("su");
            os = new DataOutputStream(process.getOutputStream());
            os.writeBytes(cmd+"\n");
            os.flush();
            os.writeBytes("exit\n");
            os.flush();

            String line;
            Log.i(TAG, "execCommand: " + "BufferedReader");
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(process.getInputStream()));

            Log.i(TAG, "bufferedReader: " + "BufferedReader readLine");
            while ((line = bufferedReader.readLine()) != null) {
                Log.i(TAG, "bufferedReader read: " + line);
            }
            Log.i(TAG, "waitFor");
            process.waitFor();
            Log.i(TAG, "waitFor END");
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (os != null)   {
                    os.close();
                }
                process.destroy();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return true;
    }

 

四、实例测试

1、java源码

package com.giada.sn_writer;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class MainActivity extends AppCompatActivity {
    private Button m_Button;
    private EditText m_EditText;
    private String TAG = "EXECUTECOMMAND";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        m_Button=(Button)findViewById(R.id.button);
        m_EditText = (EditText) findViewById(R.id.textView);

        m_Button.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v)
            {
                String str = m_EditText.getText().toString();
              //  execute_command("sn_writer write-key "+ str);
              //  playRunTime("sn_writer write-key "+ str);
                try {
                    playRunTime("ls");
                    playRunTime("cat /sys/class/power_supply/battery/voltage_now");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }
    public static String execute_command(String cmd) {
        try {
            //String keyCommand = "setprop " + propName;
            Runtime runtime = Runtime.getRuntime();
            Process proc = runtime.exec(cmd);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  cmd;
    }

   private String playRunTime(String cmd) throws Exception
   {
       //  String cmd = "adb version";
         String ret = null;
         Process p = Runtime.getRuntime().exec(cmd);
         InputStream is = p.getInputStream();
         BufferedReader reader = new BufferedReader(new InputStreamReader(is));
         String line; while ((line = reader.readLine()) != null)
         {
           //tv_result.append(line + "");
             ret = line;
             System.out.println(TAG+"  "+line);
         }
         p.waitFor();
         is.close();
         reader.close();
         p.destroy();
         return ret;
   }
}

2、执行效果

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Java中连接到Linux虚拟机并在其上执行命令,可以使用JSch库。下面是一个简单的例子: ```java import com.jcraft.jsch.*; public class SSHExample { public static void main(String[] args) { try { JSch jsch = new JSch(); String host = "your-ssh-host"; String user = "your-ssh-user"; String password = "your-ssh-password"; Session session = jsch.getSession(user, host, 22); session.setPassword(password); session.setConfig("StrictHostKeyChecking", "no"); session.connect(); String command = "ls -l"; Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(command); channel.setInputStream(null); ((ChannelExec) channel).setErrStream(System.err); InputStream in = channel.getInputStream(); channel.connect(); // 读取命令的输出 BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); channel.disconnect(); session.disconnect(); } catch (JSchException | IOException e) { e.printStackTrace(); } } } ``` 在上面的例子中,我们使用JSch库连接到SSH主机并执行命令。需要替换`your-ssh-host`,`your-ssh-user`和`your-ssh-password`为实际的SSH主机,用户名和密码。然后,我们指定要在虚拟机中执行命令,并使用`ChannelExec`执行命令。最后,我们读取命令的输出并打印到控制台上。 需要注意的是,JSch库需要在项目中包含相应的依赖项。可以在Maven或Gradle中添加JSch库的依赖项。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值