java - 如何在jsch中获取输出结果

标签 java io jsch

我正在尝试使用 jsch 获取通过 SSH 发送的命令的输出。我的问题是我需要将命令的结果放入字符串中以便稍后使用。例如,如果我发送命令“ls”,我需要字符串中的文件夹中的文件名。

我怎样才能做到这一点?

这是我的代码:

import com.jcraft.jsch.*;


public class SSHCommand2 {
public static void main(String[] args) {
    String host="host";
    String user="user";
    String password="password";


    try{


        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        JSch jsch = new JSch();
        Session session=jsch.getSession(user, host, 22);
        session.setPassword(password);
        session.setConfig(config);
        session.connect();
        System.out.println("Connected");

        Channel channel = session.openChannel("shell");
        ((ChannelShell) channel).setPty(true);

        OutputStream inputstream_for_the_channel = channel.getOutputStream();
        PrintStream commander = new PrintStream(inputstream_for_the_channel, true);
        channel.setOutputStream(System.out, true);

        channel.connect();
        commander.println("ls");

        if(channel.isClosed()){
            //if(in.available()>0) continue;
            System.out.println("exit-status: "+channel.getExitStatus());
            //break;
          }
        do {
            Thread.sleep(1000);
        } while(!channel.isEOF());
        session.disconnect();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}

最佳答案

这就是我读取命令输出的方式

编辑

1)连接服务器的方法:

public void connect (final String host){
    if(host.isEmpty())
        return;

    hostname = host;
    try{
        JSch jsch=new JSch();
        String user ="yourUserName";
        String host = "yourHost";

        Session myLocalSession=jsch.getSession(user, host, 22);
        //myLocalSession=jsch.getSession(user, "192.168.1.104", 22);

        myLocalSession.setPassword("yourPassword");

        myLocalSession.setConfig("StrictHostKeyChecking", "no");

        myLocalSession.connect(5000);   // making a connection with timeout.
        myChannel = myLocalSession.openChannel("shell");

        InputStream inStream = myChannel.getInputStream();

        OutputStream outStream = myChannel.getOutputStream();
        toChannel = new PrintWriter(new OutputStreamWriter(outStream), true);

        myChannel.connect();
        readerThread(new InputStreamReader(inStream));


        Thread.sleep(100);
        sendCommand("cd "+path);
      }
    catch(JSchException e){
        String message = e.getMessage();
        if(message.contains("UnknownHostException"))
            myParser.print(">>>>> Unknow Host. Please verify hostname.");
        else if(message.contains("socket is not established"))
            myParser.print(">>>>> Can't connect to the server for the moment.");
        else if(message.contains("Auth fail"))
            myParser.print(">>>>> Please verify login and password");
        else if(message.contains("Connection refused"))
            myParser.print(">>>>> The server refused the connection");
        else
            System.out.println("*******Unknown ERROR********");

        System.out.println(e.getMessage());
        System.out.println(e + "****connect()");
      }
    catch(IOException e)
    {
        System.out.println(e);
        myParser.print(">>>>> Error when reading data streams from the server");
    }
    catch(Exception e){
        e.printStackTrace();
    }
}

2)向服务器发送命令的方法

public void sendCommand(final String command)
{
    if(myLocalSession != null && myLocalSession.isConnected())
    {
        try {
            toChannel.println(command);
        } catch(Exception e){
            e.printStackTrace();
        }
    }
}

3)从服务器读取答案的线程方法

void readerThread(final InputStreamReader tout)
{
    Thread read2 = new Thread(){
    @Override
    public void run(){
        StringBuilder line = new StringBuilder();
        char toAppend = ' ';
        try {
            while(true){
                try {
                    while (tout.ready()) {
                        toAppend = (char) tout.read();
                        if(toAppend == '\n')
                        {
                            System.out.print(line.toString());
                            line.setLength(0);
                        }
                        else
                            line.append(toAppend);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("\n\n\n************errorrrrrrr reading character**********\n\n\n");
                }
                Thread.sleep(1000);
            }
        }catch (Exception ex) {
            System.out.println(ex);
            try{
                tout.close();
            }
            catch(Exception e)
            {}
        }
    }
    };
    read2.start();
}

您可以将 bufferedReader 与 InputStreamReader 一起使用并逐行读取。我使用无限循环,并在每次尝试读取失败后暂停一秒钟(没有来自服务器的任何内容)。

假设这三个方法都在 SessionB 类中。示例:

SessionB testConnexion = new SessionB();
testConnexion.connect();
testConnexion.sendCommand("cd myFolder");
testConnexion.sendCommand("ls");

您应该在控制台中获取文件列表。

如果您需要能够进行交互(根据输出发送命令),请查看我的帖子 here .

关于java - 如何在jsch中获取输出结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22717382/

相关文章:

java - 贾斯珀查看器 : How to set filename while saving report?

java - 将 Spring Boot Property Bean 传递给其他项目中的类

go - 关于创建文件的权限,os.FileMode 的哪个组合对应于 fopen 中的 `a`?

java - 删除字符串中的 ASCII 字符

java - 无法解析类型

c++ - 如何忽略 C++ 文件中的空格

java - 获取文件名区分大小写,拼写不区分大小写

java - 如何设置jsch终端模式?

java - 交互式服务检测显示何时在远程服务器上打开应用程序 (JSch)

java - 使用 JSch 调用 WLST 命令