java - 需要从java执行shell脚本

标签 java shell

我需要从 java 执行(运行)驻留在服务器(Solaris)中的 shell 脚本。请帮助我如何从java执行文件?我尝试过 TelnetToClient 的 sendCommand() 。所以请帮助我从 GUI 运行文件。

程序是这样的。

TelnetToPort tele = new TelnetToPort("opmer3");
tele.login("root","root");
String command_ = "/usr/bin/bash /opt/nrl/logs/applications/ns/lccommands.sh";
tele.runComm(command_);

最佳答案


如果您正在寻找为您的 java 类执行任何脚本的优化解决方案,那么您可以将 Jsch 与 Google Expect4j 库结合使用。

对于 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());             
                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;
        }
    }

希望这有帮助。
谢谢。

关于java - 需要从java执行shell脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4601436/

相关文章:

java - 如何从客户端应用程序调用 weblogic 服务器中的集群 EJB 应用程序

python - 如何在不指定文件扩展名的情况下运行 python 脚本(跨平台解决方案)?

arrays - 我可以设置多少个参数

java - 为什么 Java 的 String 有方法 length() 而不是属性 length(像数组一样?)

linux - 使用 systemctl 或服务命令在 CentOS7 中不会提示用户输入

bash - 如何更改 unix 管道将其结果发送到 split 命令的位置?

linux - 如何在 linux 上找到所有基本上是其他目录或文件的软链接(soft link)或硬链接(hard link)的文件?

java - 从 IDE 运行 Spring Web 与从 jar 文件运行 Spring Web

java - Apache POI getStringCellValue() 打印 null

java - 在 Java 中创建沙盒插件可扩展应用程序