我在使用Java中的Ganymed库测试连接时遇到了一些问题,2周前它工作正常没有问题但是现在我收到以下错误消息:
The execute request failed.
这与Ganymed“execCommand()”方法有关。当我使用WinSCP进行连接时,一切正常但尝试使用java连接会给我带来错误。我也在考虑防火墙是否也可能成为原因,只是一个想法。
我用来执行tail命令的代码如下:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
public class SSHTesting {
public static void main(String[] args) {
try{ Connection conn = new Connection("eappdev101.momentum.co.za");
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword("username", "password");
if (isAuthenticated == false) {
System.out.println("Credentials are wrong.");
}
Session sess = conn.openSession();
sess.execCommand("tail -f /logs/SystemOut.log");
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
sess.close();
conn.close();
System.out.println("Done");
}
catch(Exception ie){
System.out.println(ie.getMessage());
}
}
}
任何光线都受到高度赞赏。提前谢谢。
答案 0 :(得分:0)
对我来说它可以正常使用密钥,我认为你应该出于安全原因使用密钥
检查以下代码
private void init() throws IOException{
char privateKeyChar[] = sshPrivateKey.toCharArray();
conn = new Connection(ftpHostname,22);
conn.connect();
boolean isAuthenticated = conn.authenticateWithPublicKey(sshUsername, privateKeyChar, null);
if (isAuthenticated == false)
throw new IOException("Authentication failed.");
session = conn.openSession();
}
public String excuteCMD(String cmd) throws IOException
{
session = conn.openSession();
session.execCommand(cmd);
InputStream stdout = new StreamGobbler(session.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
while (true)
{
String line = br.readLine();
if (line == null)
break;
else
output+=line;
}
return output;
}