5
  1. I need to connect to server(username,pasw,host)-- easy

  2. enter 3-10 commands -- command="dir;date;cd;dir" is there an easier way ?, without writing 20 lines: while(smtng) { a lot of stuff+ mysterious print to scr:D }

  3. download a file-- easy

  4. write another downloaded file to the same file (add not owerride) -- any ideas how?

So to perform these increadible easy tasks, which might seem impossible if you dare to use Jsch(awsome documentation), there is a choise between Jsch,sshj,Ganymed any suggestions?

Mystery:

2) multiple commands entering

4) adding to the existing txt file more txt :D (probably there is a build in command) or not?

  /* just for download/owerride : sftpChannel.get("downloadfile.txt", "savefile.txt");*/
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
user605596
  • 259
  • 2
  • 3
  • 7
  • Just a note: I wrote some [Javadocs for JSch](http://epaul.github.com/jsch-documentation/simple.javadoc/), which might help for the documentation problem. – Paŭlo Ebermann Oct 19 '11 at 15:19

2 Answers2

5

I don't know about Ganymed. But I have used JSch extensively for remote login and script executions. I used Google's Expect4j with Jsch for executing scripts on remote machines in expect mode(send/wait). You can get the whole output of executed command or scripts in your code using JSch/Expect4j/Closures.

For jsch, go to http://www.jcraft.com/jsch/
For Expect4j, go to http://code.google.com/p/expect4j/

The following is a small code sample for logging in and executing file for remote Java class.

private Expect4j SSH(String hostname, String username,String password, int port) throws Exception {
    JSch jsch = new JSch();
    Session session = jsch.getSession(username, hostname, port);
    if (password != null) {         
        session.setPassword(password);
    }
    Hashtable<String,String> config = new Hashtable<String,String>();
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);
    session.connect(60000);
    channel = (ChannelShell) session.openChannel("shell");
    Expect4j expect = new Expect4j(channel.getInputStream(), channel.getOutputStream());
    channel.connect();      
    return expect;
}

This method will open up a SSH stream to the remote server which will be used by expect4j for sending commands.

private boolean executeCommands() {
        boolean isSuccess = true;
        Closure closure = new Closure() {
            public void run(ExpectState expectState) throws Exception {
                buffer.append(expectState.getBuffer());//buffer is string buffer for appending output of executed command             
                expectState.exp_continue();
            }
        };
        List<Match> lstPattern =  new ArrayList<Match>();
        String[] regEx = SSHConstants.linuxPromptRegEx;  
        if (regEx != null && regEx.length > 0) {
            synchronized (regEx) {
                for (String regexElement : regEx) {//list of regx like,  :>, /> etc. it is possible command prompts of your remote machine
                    try {
                        RegExpMatch mat = new RegExpMatch(regexElement, closure);
                        lstPattern.add(mat);                        
                    } catch (MalformedPatternException e) {                     
                        return false;
                    } catch(Exception e) {                      
                        return false;
                    }
                }
                lstPattern.add(new EofMatch( new Closure() { // should cause entire page to be collected
                    public void run(ExpectState state) {
                    }
                }));
                lstPattern.add(new TimeoutMatch(defaultTimeOut, new Closure() {
                    public void run(ExpectState state) {
                    }
                }));
            }
        }
        try {
            Expect4j expect = SSH(objConfig.getHostAddress(), objConfig.getUserName(), objConfig.getPassword(), SSHConstants.SSH_PORT);
            expect.setDefaultTimeout(defaultTimeOut);       
            if(isSuccess) {
                for(String strCmd : lstCmds)
                    isSuccess = isSuccess(lstPattern,strCmd);
            }
            boolean isFailed = checkResult(expect.expect(lstPattern));
            return !isFailed;
        } catch (Exception ex) {            
            return false;
        } finally {
            closeConnection();
        }
    }


private boolean isSuccess(List<Match> objPattern,String strCommandPattern) {
        try {   
            boolean isFailed = checkResult(expect.expect(objPattern));

            if (!isFailed) {
                expect.send(strCommandPattern);         
                expect.send("\r");              
                return true;
            } 
            return false;
        } catch (MalformedPatternException ex) {    
            return false;
        } catch (Exception ex) {
            return false;
        }
}  
Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
Nikunj
  • 3,100
  • 2
  • 20
  • 19
  • 1
    Google's Expect4j is used for executing commands subsequently. Suppose, you have 10 shell commands and you want to execute on remote linux machine. After you post one command, you have to wait for the command output. Means send/wait functionality. Also you can get output of command on your machine using expect4j with closures. You can get log of all the commands you have executed on you machine and save it. – Nikunj Feb 24 '11 at 07:11
  • Hi, @nIKUNJ what exactly /Expect4j/Clousers – user615927 Feb 24 '11 at 07:02
  • This seems like an amazing thing, any examples :) ? – user605596 Mar 03 '11 at 20:01
  • I get this error when i try to compile the first example(yes i have imported the expect4j jar )run: Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/oro/text/regex/Perl5Matcher at expect4j.Expect4j.(Expect4j.java:37) at expect4j.Expect4j.(Expect4j.java:61) at newpkg.Main.SSH(Main.java:41) at newpkg.Main.main(Main.java:54) – user605596 Mar 06 '11 at 17:38
  • To compile these examples you need to import oro-2.0.8.jar!!!! (use 3-4 link from google, other top 2 are there just for confusion) solved my problem :) – user605596 Mar 06 '11 at 17:54
  • @user605596 if you find any answer helpful, then please acknowledge it. – Nikunj Mar 10 '11 at 06:35
  • @nLKUNJ I don't find not working examples usefull, do you? to start with SSHConstants.linuxPromptRegEx; does not exist, it's SshConstants, furthermore .linuxPromptRegEx doesn't exist either... and can't you write about jars which you need to import in order to make this work or do you assume that searching for jar for 30 min , then searching again when that jar doesn't include .linuxPromt.... is very interesting?! – user605596 Mar 27 '11 at 17:49
  • Is it possible to get output of each command rather than just storing in one buffer? – MalTec Jul 21 '14 at 10:47
1

I can't comment on the others but Ganymed works very well indeed.

Gray
  • 115,027
  • 24
  • 293
  • 354
user207421
  • 305,947
  • 44
  • 307
  • 483
  • 2
    Maintenance is stopped (support is most likely the same). So any serious issue will result in refusing the lib. – Denys S. Mar 30 '11 at 09:51
  • @den-javamaniac: Actually it isn't. It says on the web site 'Please visit the Cleondris website, www.cleondris.ch, in case you need updates & support', and the Contact page at that site has a release as of August 2010. There was never any support, it's open source. – user207421 Mar 30 '11 at 22:50
  • oh yeah, haven't seen it from the first time. – Denys S. Mar 31 '11 at 12:14
  • @downvoter Please explain. I *can* comment on the others? Ganymede *doesn't* work very well indeed for me? Difficult to know what the problem could be here. – user207421 Oct 11 '16 at 11:01