简体   繁体   English

将输入键从 Java 传递到 Shell 脚本

[英]pass enter key from Java to Shell script

I am trying a Java program to run multiple commands in unix environment.我正在尝试使用 Java 程序在 unix 环境中运行多个命令。 I would need to pass 'ENTER' after each command.我需要在每个命令后传递“ENTER”。 Is there some way to pass enter in the InputStream.有什么方法可以在 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.当我做ls -l时,我想在这里添加回车,以便执行命令。 getInputStream is a method to convert String into InputStream. getInputStream 是一种将 String 转换为 InputStream 的方法。

Any help will be appreciated.任何帮助将不胜感激。

According to the JSch javadoc, you must call setInputStream() or getOutputStream() before connect() .根据 JSch javadoc,您必须在connect()之前调用setInputStream()getOutputStream() connect() You can only do one of these, once.您只能执行其中之一,一次。

For your purposes, getOutputStream() seems more appropriate.对于您的目的, getOutputStream()似乎更合适。 Once you have an OutputStream, you can wrap it in a PrintWriter to make sending commands easier.拥有 OutputStream 后,您可以将其包装在 PrintWriter 中,以便更轻松地发送命令。

Similarly you can use channel.getInputStream() to acquire an InputStream from which you can read results.同样,您可以使用channel.getInputStream()获取一个 InputStream,您可以从中读取结果。

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:如果您决定使用setInputStream()而不是getOutputStream()那么您只能这样做一次,因此您必须将所有行放入一个字符串中:

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

(I don't think you need \\r , but add it back in if necessary) (我认为您不需要\\r ,但如有必要,请将其重新添加)

If you're not familiar with working with streams, writers and readers, do some study on these before working with JSch.如果您不熟悉使用流、写入器和读取器,请在使用 JSch 之前对这些进行一些研究。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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