【问题标题】:Android execute shell in context of previous command from appAndroid在应用程序的上一个命令的上下文中执行shell
【发布时间】:2013-11-25 05:34:20
【问题描述】:

我知道如何从 Android 应用程序的 shell 中执行命令

shell.exec("ls /");

以及如何从中读取响应

new BufferedReader(new InputStreamReader(_process.getInputStream())).readLine();

但我有一个 shell 应用程序,它在运行后需要额外的用户输入。而且我想知道如何向同一个 shell 命令发送额外的输入。

例如:

cp /abc/ /a/abc/

假设该命令要求用户通过输入额外的Y 来确认覆盖,该怎么做?

【问题讨论】:

    标签: android shell android-context execute


    【解决方案1】:

    尝试通过 shell 发送多个命令。这通过 JSCH 客户端进行 ssh 工作

     Channel channel=session.openChannel("shell");
                OutputStream ops = channel.getOutputStream();
                PrintStream ps = new PrintStream(ops, true);
    
                 channel.connect();
                 ps.println("mkdir folder"); 
                 ps.println("dir");
         //give commands to be executed inside println.and can have any no of commands sent.
                              ps.close();
    
                 InputStream in=channel.getInputStream();
                 byte[] bt=new byte[1024];
    
    
                 while(true)
                 {
    
                 while(in.available()>0)
                 {
                 int i=in.read(bt, 0, 1024);
                 if(i<0)
                  break;
                    String str=new String(bt, 0, i);
                  //displays the output of the command executed.
                    System.out.print(str);
    
    
                 }
                 if(channel.isClosed())
                 {
    
                     break;
                }
                 Thread.sleep(1000);
                 channel.disconnect();
                 session.disconnect();   
                 }
    

    【讨论】:

    • 嗨。感谢重播,但是thou命令立即被一一发送。但我想要的是发送命令,比如cp,然后读取输出,一旦输出包含Do you want to rewrite file,我发送响应Y,这可能吗,我能够读取和分析响应,但是我无法发送响应以便它在问题给出的上下文中理解它,如果我使用shell.exec("Y"); 它会给出错误。 (我知道你可以使用标志来覆盖所有,但我每次都必须询问用户)。
    • 我认为您的要求是不可能的,因为这些功能仅适用于命令而不适用于用户输入。
    • 好吧,也许可以隐藏在后台运行终端shell,并像用户在真实shell中输入一样发送输入,这可能吗?
    【解决方案2】:

    试试

    Process process = Runtime.getRuntime().exec(commandLine);
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-17
      • 2011-02-06
      • 1970-01-01
      • 1970-01-01
      • 2011-06-04
      • 1970-01-01
      相关资源
      最近更新 更多