【发布时间】:2012-12-13 05:06:17
【问题描述】:
我正在开发一个 JSP Web 应用程序,用于监控我办公室中不同 HP-ux 和 Linux 服务器的系统参数。我正在使用 jsch 来
在远程系统上执行命令。我的问题是 jsch 对于 ntpq -p 之类的命令返回 null。
我正在尝试使用命令ntpq -p | tail -1 | awk '{ print $1 }' 获取与系统同步的服务器。但它返回null。但是像这样的命令
mpstat | tail -1 | awk '{ print $12 }' 工作正常并返回结果。谁能告诉我我做错了什么以及任何可能的解决方法...?
这是我用于此目的的代码!
package com.bpcl.sysmon;
import java.io.IOException;
import java.io.InputStream;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
public class Sys
{
String line;
String host="**.**.**.***";
String user="******";
String password="***********";
String result = null;
public String getdata(String command1) throws IOException
{
try
{
result = null;
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
com.jcraft.jsch.Session session=jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig(config);
session.connect();
Channel channel=session.openChannel("exec");
((ChannelExec) channel).setCommand(command1);
channel.setInputStream(null);
((ChannelExec)channel).setErrStream(System.err);
InputStream in=channel.getInputStream();
channel.connect();
byte[] tmp=new byte[1024];
while(true)
{
while(in.available()>0){
int i=in.read(tmp, 0, 1024);
if(i<0)break;
result = (new String(tmp, 0, i));
}
if(channel.isClosed())
{
System.out.println("exit-status: "+channel.getExitStatus());
break;
}
try
{
Thread.sleep(1000);}catch(Exception ee){}
}
channel.disconnect();
session.disconnect();
System.out.println("DONE");
}
catch(Exception e)
{
e.printStackTrace();
}
return result;
}
public String getcpu(boolean linux)
{
String res1 = null;
try {
if(linux)
res1 = getdata("mpstat | tail -1 | awk '{ print $12 }'");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return res1;
}
public String getntp(boolean linux)
{
String res1 = null;
try {
if(linux)
res1 = getdata("ntpq -p | tail -1 | awk '{ print $1}'");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return res1;
}
【问题讨论】:
-
你能指定什么返回 null 吗? (变量)请。
-
函数 getntp(boolean ) 返回 null。它从函数 getdata(string) 中获取值,其中变量“result”被初始化为“null”。它返回 null 因为命令没有被 jsch 正确执行。
-
我已经将您的代码与我目前正在使用的代码进行了比较,并测试了您的命令并且它们正在运行。您的代码似乎几乎完全相同。您可以在 ssh 日志中验证它是否正确连接,也可以测试例如“whoami”。
-
任何关于我可能做错的事情......?我还检查了 ssh 日志及其正确连接...!