【发布时间】:2017-08-21 16:22:36
【问题描述】:
我想从 linux shell 上的命令读取 json 输出。
我使用jcraft建立ssh连接,使用channel执行telnet命令。
String host="<host>";
String user="<user>";
String password="<pass>";
String command1="telnet <ip>";
try{
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
Session session=jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig(config);
session.connect();
System.out.println("Connected");
Channel channel=session.openChannel("exec");
((ChannelExec)channel).setCommand(command1);
channel.setInputStream(null);
((ChannelExec)channel).setErrStream(System.err);
InputStream in=channel.getInputStream();
channel.connect();
DataOutputStream dataOut = new DataOutputStream(channel.getOutputStream());
byte[] tmp=new byte[1024];
int count = 0;
int count1 = 0;
while(true){
while(in.available()>0){
int i=in.read(tmp, 0, 1024);
if(i<0)break;
System.out.println(new String(tmp, 0, i));
String asksForUsername = new String(tmp, 0, i);
if(asksForUsername.contains("login") && count <= 0) {
dataOut.writeBytes("<username>");
dataOut.writeBytes("\n");
dataOut.flush();
count++;
}
if(asksForUsername.contains("Password") && count1 <= 0) {
dataOut.writeBytes("<password>");
dataOut.writeBytes("\n");
dataOut.flush();
count1++;
}
if(count == 1 && count1 == 1) {
count++;
count1++;
dataOut.writeBytes("<shell command to get the json response>");
dataOut.writeBytes("\n");
dataOut.flush();
}
}
if(channel.isClosed()){
System.out.println("exit-status: "+channel.getExitStatus());
break;
}
try{Thread.sleep(1000);}catch(Exception ee){}
}
channel.disconnect();
session.disconnect();
count = 0;
count1 = 0;
}catch(Exception e){
e.printStackTrace();
}
执行命令以使用写入字节获取 Json 响应后,我需要读取输出并将其分配给 json 对象吗?有可能吗。
提前致谢。
问候
【问题讨论】:
标签: java json linux ssh telnet