将enter键从Java传递到Shell脚本
我正在尝试一个Java程序在unix环境中运行多个命令。我需要在每个命令后传递'ENTER'。是否有某种方法可以在InputStream中传递enter将enter键从Java传递到Shell脚本,java,unix,jsch,Java,Unix,Jsch,我正在尝试一个Java程序在unix环境中运行多个命令。我需要在每个命令后传递'ENTER'。是否有某种方法可以在InputStream中传递enter JSch jsch=new JSch(); Session session=jsch.getSession("MYUSERNAME", "SERVER", 22); session.setPassword("MYPASSWORD"); Properties config = new
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();
当我执行ls-l时,我想在这里添加enter,以便执行命令。
getInputStream是一种将字符串转换为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();
任何帮助都将不胜感激。根据JSch javadoc,您必须在
connect()
之前调用setInputStream()
或getOutputStream()
。你只能做其中一个,一次
出于您的目的,getOutputStream()
似乎更合适。一旦有了OutputStream,就可以将其包装在PrintWriter中,以便更轻松地发送命令
类似地,您可以使用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");
如果决定使用setInputStream()
而不是getOutputStream()
,则只能执行一次,因此必须将所有行放入一个字符串中:
channel.setInputStream(getInputStream("ls -l\npwd\n"));
(我认为您不需要\r
,但如果需要,请将其添加回)
如果您不熟悉使用流、编写器和读取器,请在使用JSch之前对其进行一些研究。您将enter('\n')发送到输入流。它只会在命令行中创建一个新行。它不执行enter。您的意思是要将enter发送到shell的输入?不清楚你在问什么。试着发布一段(最少的)代码并解释什么不起作用。我已经修改了问题以添加程序。它当前处于\r\n状态,不工作。它只是在创造一条新的路线