简体   繁体   中英

pass enter key from Java to Shell script

I am trying a Java program to run multiple commands in unix environment. I would need to pass 'ENTER' after each command. Is there some way to pass enter in the InputStream.

        JSch jsch=new JSch();
        Session session=jsch.getSession("MYUSERNAME", "SERVER", 22);
        session.setPassword("MYPASSWORD");
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();

        Channel channel= session.openChannel("shell");
        channel.setInputStream(getInputStream("ls -l"));
        channel.setInputStream(getInputStream("\r\n"));
        channel.setInputStream(getInputStream("pwd"));
        channel.setInputStream(getInputStream("\r\n"));
        channel.connect();

When I do ls -l, I want to add enter here, so that the command is executed. getInputStream is a method to convert String into InputStream.

Any help will be appreciated.

According to the JSch javadoc, you must call setInputStream() or getOutputStream() before connect() . You can only do one of these, once.

For your purposes, getOutputStream() seems more appropriate. Once you have an OutputStream, you can wrap it in a PrintWriter to make sending commands easier.

Similarly you can use channel.getInputStream() to acquire an InputStream from which you can read results.

OutputStream os = channel.getOutputStream();
PrintWriter writer = new PrintWriter(os);
InputStream is = channel.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
channel.connect();
writer.println("ls -l");
String response = reader.readLine();
while(response != null) {
    // do something with response
    response = reader.readLine();
}
writer.println("pwd");

If you're determined to use setInputStream() instead of getOutputStream() then you can only do that once, so you'll have to put all your lines into one String:

    channel.setInputStream(getInputStream("ls -l\npwd\n"));

(I don't think you need \\r , but add it back in if necessary)

If you're not familiar with working with streams, writers and readers, do some study on these before working with JSch.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM