我是JSch的新手。我试图在服务器上运行一些命令,我从其他系统获得输入。我正在做的是获取这些命令并将它们作为参数传递给java方法。对于Eg:
public String readFileFromPath(String server, String path,
String fileName);
首先我们必须cd到'path',然后我们需要从路径上的文件中读取一些特定的内容。为了实现这一点,我做了如下:
Session session = sshOperations.getSessionWithTimeout(USER,server,SSHPORT,1000);
Channel shellChannel = sshOperations.getShellChannel(session);
InputStream in = new PipedInputStream();
PipedOutputStream consoleInput = new PipedOutputStream((PipedInputStream) in);
OutputStream out = new PipedOutputStream();
BufferedReader consoleOutput = new BufferedReader(new InputStreamReader(new PipedInputStream((PipedOutputStream) out)));
shellChannel.setInputStream(in);
shellChannel.setOutputStream(out);
shellChannel.connect(1000);
consoleInput.write(("cd "+path).getBytes());
// first While
while ((line = consoleOutput.readLine()) != null)
{
System.out.println("check "+ line);
}
// execute second command
consoleInput.write("cat some.properties".getBytes());
// second While
while ((line = consoleOutput.readLine()) != null)
{
System.out.println("check "+ line);
}
现在我所知道的是每当我连接到该服务器时,我都会得到一个欢迎文本:
"You are using <serverName> server.
Please contact admin for any issues"
所以,在第一个while循环之后,我的cd命令运行并打印上面提到的消息。但是,在此之后它等待输出流的更多输出(它在此时停留)并且输出流不能产生任何东西,直到我运行另一个命令。
不知何故,我想退出第一个while循环而不编写消耗2行(固定行)的逻辑。至于下一个命令,我不知道将在流中输出多少行。
请建议获得所需输出的逻辑,即我运行一个命令,一些逻辑消耗它然后我得到运行另一个命令,依此类推,直到执行所有作为参数的命令。
有没有其他方法可以达到同样的目的?
谢谢
不要使用“shell”频道。 “shell”通道旨在实现交互式会话(因此是欢迎消息),而不是自动执行命令。
要自动执行命令,请使用“exec”通道。见Multiple commands through JSch shell。
虽然你实际上不需要多个命令。没有必要使用cd
。只需在cat
命令中使用完整路径即可
ChannelExec channel = (ChannelExec) session.openChannel("exec");
channel.setCommand("cat " + path + "/some.properties");
channel.connect();
实际上,如果要读取文件内容,请使用SFTP,而不是像cat
那样运行控制台命令。 SFTP是一种通过SFTP访问文件的标准化API。