0

I am trying connect interactive connection with SSH using java code. I used jsch and expect builder. but it is howing me "error messagejava.io.EOFException: Input closed" in expectbuilder. But same thing I connect through putty it works fine. can anyone help me where I am going wrong? Here's my code

package src.main.java;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.concurrent.TimeUnit;

import javax.swing.JOptionPane;

import net.sf.expectit.Expect;
import net.sf.expectit.ExpectBuilder;
import net.sf.expectit.matcher.Matcher;
import net.sf.expectit.matcher.Matchers;
import net.sf.saxon.functions.Contains;

import com.eviware.soapui.support.scripting.SoapUIScriptEngine;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UserInfo;


public class SSHConnect  {




    //String remoteFile="/home/john/test.txt";

public static void main(String[] args) {
    String user = "user";
    String password = "password";
    String host = "hostname";
    int port=22;

    try
    {  
        JSch jsch = new JSch();
        //       jsch.

        Session session = jsch.getSession(user, host, port);
        session.setPassword(password);
        session.setConfig("StrictHostKeyChecking", "no");
        System.out.println("Establishing Connection...");
        session.connect();
        Channel channel=session.openChannel("exec");



        channel.connect();
        System.out.println("chanel connect");

         Expect expect = new ExpectBuilder()
         .withInputs(channel.getInputStream())
         .withOutput(channel.getOutputStream())
         .withTimeout(10, TimeUnit.SECONDS)
         .withExceptionOnFailure()

         .build();
         expect.interact();



        Expect p= expect.sendLine("ssh serverName");
        String check1=expect.expect(contains("Could"));
         expect.sendLine("yes");
         String check= expect.expect(contains("password"));
         expect.sendLine("password");
        System.out.println("check"+check1);





    }
    catch(Exception e){System.err.print("error message"+ e);}
}

    private static Matcher contains(String string) {
        Matcher matcher=Matchers.contains(string);
        return matcher;
    }
}
Alexey Gavrilov
  • 10,593
  • 2
  • 38
  • 48
LowCool
  • 1,187
  • 5
  • 25
  • 51

1 Answers1

0

Try changing the JSch channel type from "exec" to "shell".

Please follow this example.

Alexey Gavrilov
  • 10,593
  • 2
  • 38
  • 48