![](/img/trans.png)
[英]I am losing data when going from constructor to main method in a different class. What is happening?
[英]I have a problem with the java SSHClient class, specifically the Expect method does not return data as espected, what could be happening?
我已經使用 java 的 SSHClient class 連接到瞻博網絡路由器,當在膩子控制台中輸入控制台時,它返回結果沒有問題,但是當從 ZD52387880E1EA221388199 返回的內容時不打印,你能告訴我該怎么做嗎?
我分享了 ssh class 來指導您,以防您遇到任何問題:
package com.mycompany;
import static net.sf.expectit.matcher.Matchers.contains;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.connection.channel.direct.Session;
import net.schmizz.sshj.connection.channel.direct.Session.Shell;
import net.schmizz.sshj.transport.verification.PromiscuousVerifier;
import net.sf.expectit.Expect;
import net.sf.expectit.ExpectBuilder;
public class sshj {
/**
* Launch Commands to Provisioning
*
* @param host
* @param port
* @param user
* @param password
* @param commands
* @param splitBy
* @return result
*/
public static String launchCommands(String host, Integer port, String user, String password, String commands,
String commandsSplitBy, String expectSplitBy, Integer timeoutInSeconds) {
String result = "";
StringBuilder wholeBuffer = new StringBuilder();
SSHClient mSSSHClient = new SSHClient();
mSSSHClient.addHostKeyVerifier(new PromiscuousVerifier());
Session mSession = null;
Shell mShell = null;
Expect mExpect = null;
String[] splitCommands = commands.split(commandsSplitBy);
try {
mSSSHClient.connect(host, port);
mSSSHClient.authPassword(user, password);
mSession = mSSSHClient.startSession();
mShell = mSession.startShell();
mExpect = new ExpectBuilder()
.withOutput(mShell.getOutputStream())
.withInputs(mShell.getInputStream())
.withEchoInput(wholeBuffer)
.withEchoOutput(wholeBuffer)
// .withEchoInput(System.out)
// .withEchoOutput(System.err)
.withExceptionOnFailure()
.withTimeout(timeoutInSeconds, TimeUnit.SECONDS).build();
// When expectSplitBy is equals to ""
if ("".equalsIgnoreCase(expectSplitBy)) {
for (String commandExpect : splitCommands) {
mExpect.sendLine(commandExpect);
}
} else { // When expectSplitBy is not equals to ""
for (String commandExpect : splitCommands) {
String[] commandExpectSplit = commandExpect.split(expectSplitBy);
mExpect.sendLine(commandExpectSplit[0]);
mExpect.expect(contains(commandExpectSplit[1]));
}
}
mShell.close();
mSession.close();
mSSSHClient.disconnect();
result = wholeBuffer.toString();
} catch (IOException e) {
result = wholeBuffer.toString().concat(" The Exception is> ").concat(e.toString());
e.printStackTrace();
try {
mExpect.sendLine("exit");
mShell.close();
mSession.close();
mSSSHClient.disconnect();
} catch (IOException e1) {
e1.printStackTrace();
}
}
return result;
}
}
我發現問題是發送的命令開頭包含一些奇怪的字符,看起來像一個空格,我可以消除它們,class 的功能執行沒有問題。
我標記了 mule,因為這是我正在使用這個 class 的地方,我知道它來自第三方,這就是為什么我共享所有代碼以便您可以進行測試的原因。 如果您沒有明確我的問題,我感到非常抱歉。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.