在网上查找后,可以通过以下方法获取返回值! 我的需求是块表达式,所以我需要完成这个jar包,然后运行另一个代码。 因此,通过以下方法实现
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import Java.io.input streamreader;
import Java.io.unsupportedencodingexception;
importorg.Apache.com mons.lang.string utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.ethz.ssh2. channel condition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2. stream gobbler;
publicstringexecshell _ new (string cmd ) {
字符串结果=' ';
try {
if(login () ) ) )。
Session sess=conn.openSession (; //打开会话
sess.execcommand(cmd; //执行命令
inputstream stdout=sess.get stdout (;
inputstream stderr=sess.get stderr (;
byte[] buffer=new byte[100];
while (真)。
if () (stdout.available ) )==0) ) 0
int conditions=sess.wait for condition (channel condition.stdout _ data |
channel condition.stderr _ data|channel condition.eof,1000*5;
if ((conditionschannelcondition.time out )!=0}{
logger.debug (execshell _ new : time outbreak! ' );
布雷克; //超时后退出循环,使脚本能够在超时时间内完成执行
}
if ((conditionschannelcondition.eof )!=0}{
if () conditions (channel condition.stdout _ data |
ChannelCondition.STDERR_DATA ) (==0) {
logger.debug (execshell _ new : break! ' );
布雷克;
}
}
}
while(stdout.available ) )0) {
intlen=stdout.read(buffer );
if(len0) {
//system.err.write(buffer,0,len );
结果=新字符串(buffer,0,len );
logger.debug (execshell _ new : result={ },result );
}
}
while(stderr.available ) )0) {
intlen=stderr.read(buffer );
if(len0) {
//system.err.write(buffer,0,len );
结果=新字符串(buffer,0,len );
logger.debug (execshell _ new : result={ },result );
}
}
}
logger.debug ('远程运行shll脚本或命令的结果,result={},result );
}
}catch(ioexceptione ) {
e .打印堆栈跟踪(;
logger.error ('远程运行shll脚本或命令异常! msg={} ',e;
}
返回结果;
}