将参数从Java代码传递到接受命令行输入的Shell脚本

时间:2019-04-11 06:31:12

标签: java linux jsch expectj

我想将名称传递给接受命令行输入的shell脚本。 我想要的输出是我应该能够将Java代码中的名称发送到脚本。

我是JSch和ExpectJ的新手

下面是我的shell脚本:

! / bin / bash

回显“名称:” 读名字 回显“输入的名称:$ name”

这是java代码:

public static void main(String[] args) {

    String flag = "";
    try {
        /**
         * Create a new Jsch object This object will execute shell commands
         * or scripts on server
         */
        JSch jsch = new JSch();

        Session session = jsch.getSession("xxxx",
                "xxxxxx", xx);
        session.setConfig("StrictHostKeyChecking", "no");
        session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password,gssapi-with-mic");
        session.setPassword("mcts@123");
        session.connect();

        if (session.isConnected()) {
            Channel channel = session.openChannel("exec");
            ((ChannelExec) channel).setCommand("cd /home/Inder; ./hello.sh");
            ((ChannelExec) channel).setErrStream(System.err);

            InputStream in = channel.getInputStream();

            /*channel.connect();
            if (channel.isConnected())
                System.out.println("Channel connected");*/
            ExpectJ exp = new ExpectJ();
            Spawn s = exp.spawn(channel);
            s.expect("Name:");
            s.send("abcd");
           // s.expect("Entered name:");
            System.out.println("New Text : " + s.getCurrentStandardOutContents());
            s.stop();
            channel.disconnect();
            session.disconnect();
        } else {
            flag = "NATL";// Not able to Login(NATL)

        }
        // retrieve the exit status of the remote command corresponding to
        // this channel

    }catch(JSchException e){
        flag = "NATL";
        e.printStackTrace();
    }
    catch (Exception e ) {
        e.printStackTrace();
        System.err.println("Error: " + e.getMessage());

    }
}

当前输出为: 名称:/ *来自脚本的回显* /
新文本:名称:/ 这是来自s.getCurrentStandardOutContents() /

0 个答案:

没有答案