Jsch、SSHJ 或 Ganymed SSH-2?

发布于 2024-10-19 07:20:40 字数 528 浏览 4 评论 0原文

  1. 我需要连接到服务器(用户名,pasw,主机)-- 简单

  2. 输入 3-10 个命令 -- 命令="dir;date;cd;dir" 有没有更简单的方法?,无需编写 20 行: while(smtng) { 很多东西+神秘打印到 scr:D }

  3. 下载文件 - 简单

  4. 将另一个下载的文件写入同一个文件(添加而不是 owerride) - 有什么想法吗?

因此,要执行这些令人难以置信的简单任务,如果您敢于使用 Jsch(很棒的文档),这似乎是不可能的,在 Jsch、sshj、Ganymed 之间有一个选择,有什么建议吗?

谜团:

2)输入多个命令

4)向现有txt文件添加更多txt:D(可能有内置命令)或没有?

  /* just for download/owerride : sftpChannel.get("downloadfile.txt", "savefile.txt");*/
  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");*/

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

南渊 2024-10-26 07:20:40

我不知道Ganymed。
但我广泛使用 JSch 进行远程登录和脚本执行。我使用 Google 的 Expect4j 和 Jsch 在期望模式(发送/等待)下在远程计算机上执行脚本。您可以使用 JSch/Expect4j/Closures 获取代码中执行的命令或脚本的完整输出。

对于 jsch,请访问 http://www.jcraft.com/jsch/
对于 Expect4j,请访问 http://code.google.com/p/expect4j/

以下是用于登录并执行远程 Java 类文件的小代码示例。

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;
}

此方法将打开一个到远程服务器的 SSH 流,expect4j 将使用该流来发送命令。

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;
        }
}  

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;
        }
}  
烟沫凡尘 2024-10-26 07:20:40

我无法评论其他的,但 Ganymed 确实效果很好。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文