通过JSch shell的多个命令

问题描述 投票:12回答:4

我试图使用JSch库通过SSH协议执行多个命令。但我似乎陷入困境,无法找到任何解决方案。 setCommand()方法每个会话只能执行单个命令。但我想按顺序执行命令,就像Android平台上的connectbot应用程序一样。到目前为止我的代码是:

package com.example.ssh;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Properties;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class ExampleSSH extends Activity {
    /** Called when the activity is first created. */
    EditText command;
    TextView result;
    Session session;
    ByteArrayOutputStream baos;
    ByteArrayInputStream bais;
    Channel channel;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        bais = new ByteArrayInputStream(new byte[1000]);
        command = (EditText) findViewById(R.id.editText1);
        result  = (TextView) findViewById(R.id.terminal);
    }

    public void onSSH(View v){
        String username = "xxxyyyzzz";
        String password = "aaabbbccc";
        String host     = "192.168.1.1"; // sample ip address
        if(command.getText().toString() != ""){
            JSch jsch = new JSch();
            try {
                session = jsch.getSession(username, host, 22);
                session.setPassword(password);

                Properties properties = new Properties();
                properties.put("StrictHostKeyChecking", "no");
                session.setConfig(properties);
                session.connect(30000);

                channel = session.openChannel("shell");
                channel.setInputStream(bais);
                channel.setOutputStream(baos);
                channel.connect();

            } catch (JSchException e) {
                // TODO Auto-generated catch block
                Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
            }
        }
        else{
            Toast.makeText(this, "Command cannot be empty !", Toast.LENGTH_LONG).show();
        }
    }

    public void onCommand(View v){
        try {
            bais.read(command.getText().toString().getBytes());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        baos = new ByteArrayOutputStream();
        channel.setOutputStream(baos);
        result.setText(baos.toString());

    }
}

代码似乎连接到服务器,但我认为输入和输出数组缓冲区存在一些问题,因为根本没有输出。有人可以指导我如何正确处理服务器的输入和输出以获得所需的输出?

java android shell ssh jsch
4个回答
12
投票

该命令是一个String,可以是远程shell接受的任何内容。尝试

cmd1 ; cmd2 ; cmd3

按顺序运行几个命令。要么

cmd1 && cmd2 && cmd3

运行命令直到一个失败。

即使这可能有效:

cmd1
cmd2
cmd3

或者在Java中:

channel.setCommand("cmd1\ncmd2\ncmd3");

旁注:不要将密码和用户名放入代码中。将它们放入属性文件并使用系统属性指定属性文件的名称。这样,您可以将文件保留在项目之外,并确保密码/用户名不会泄漏。


11
投票

如果您不必区分各个命令的输入或输出,那么Aaron的答案(连续给出所有命令,由\n;分隔)都可以。

如果你必须单独处理它们,或者在之前的命令完成之前不知道后面的命令:你可以在同一个Session(即连接)上一个接一个地打开多个exec-Channels(即在关闭之前的那个之后) 。每个人都有自己的命令。 (但是它们不共享环境,所以第一个中的cd命令对后来的命令没有影响。)

您只需要注意使用Session对象,而不是为每个命令创建一个新对象。

另一种选择是shell channel,然后将各个命令作为输入传递给远程shell(即通过流)。但是你必须注意不要将输入混合到一个命令和下一个命令(即只有当你知道命令正在做什么时,或者如果你有一个交互式用户可以为命令提供输入和下一个命令,并知道何时使用哪一个。)


3
投票

设置一个SCPInfo对象来保存用户名,密码,端口:22和ip。

    List<String> commands = new ArrayList<String>();
    commands.add("touch test1.txt");
    commands.add("touch test2.txt");
    commands.add("touch test3.txt");
    runCommands(scpInfo, commands);

public static void runCommands(SCPInfo scpInfo, List<String> commands){
    try {
        JSch jsch = new JSch();
        Session session = jsch.getSession(scpInfo.getUsername(), scpInfo.getIP(), scpInfo.getPort());
        session.setPassword(scpInfo.getPassword());
        setUpHostKey(session);
        session.connect();

        Channel channel=session.openChannel("shell");//only shell  
        channel.setOutputStream(System.out); 
        PrintStream shellStream = new PrintStream(channel.getOutputStream());  // printStream for convenience 
        channel.connect(); 
        for(String command: commands) {
            shellStream.println(command); 
            shellStream.flush();
        }

        Thread.sleep(5000);

        channel.disconnect();
        session.disconnect();
    } catch (Exception e) { 
        System.err.println("ERROR: Connecting via shell to "+scpInfo.getIP());
        e.printStackTrace();
    }
}

private static void setUpHostKey(Session session) {
    // Note: There are two options to connect
    // 1: Set StrictHostKeyChecking to no
    //    Create a Properties Object
    //    Set StrictHostKeyChecking to no
    //    session.setConfig(config);
    // 2: Use the KnownHosts File
    //    Manually ssh into the appropriate machines via unix
    //    Go into the .ssh\known_hosts file and grab the entries for the hosts
    //    Add the entries to a known_hosts file
    //    jsch.setKnownHosts(khfile);
    java.util.Properties config = new java.util.Properties();
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);
}

0
投票

避免尽可能使用“shell”通道。 “shell”通道旨在实现交互式会话,而不是自动执行命令。使用“shell”通道,您将面临许多不必要的副作用。

要自动执行命令,请使用“exec”通道。


通常,您可以根据需要打开任意数量的“exec”通道,使用每个通道执行一个命令。您可以按顺序打开通道,也可以并行打开通道。

有关“exec”通道使用的完整示例,请参阅JSch Exec.java example

这样,每个命令都在隔离的环境中执行。什么可能是有利的,但在某些情况下也可能是不合需要的。


如果需要以先前命令影响以后命令的方式执行命令(例如更改工作目录或设置环境变量),则必须在同一通道中执行所有命令。为此使用服务器shell的适当构造。在大多数系统上,您可以使用分号:

execChannel.setCommand("command1 ; command2 ; command3");

在* nix服务器上,您还可以使用&&使以下命令仅在先前命令成功时执行:

execChannel.setCommand("command1 && command2 && command3");

另见Execute a list of commands from an ArrayList using JSch exec in Java


最复杂的情​​况是,当命令相互依赖并且您需要在继续执行其他命令之前处理先前命令的结果。

当你有这样的需求时,它通常表明设计不好。如果这真的是解决您问题的唯一方法,请认真思考。或者考虑实现服务器端shell脚本来实现逻辑,而不是从Java代码远程执行。 Shell脚本具有更强大的技术来检查以前命令的结果,然后在JSch中使用SSH接口。

无论如何,请参阅JSch Shell channel execute commands one by one testing result before proceeding


旁注:不要使用StrictHostKeyChecking=no。见JSch SFTP security with session.setConfig("StrictHostKeyChecking", "no");

© www.soinside.com 2019 - 2024. All rights reserved.