public class Connectshell{
public static boolean shShell(String shellScript){
try{
log.info("执行脚本路径为:"+shellScript);
boolean flag = false;
Session jschSession = null;
InputStream in = null;
JSch jsch = new JSch();
jschSession = jsch.getSession(SSHConfigUtil.userName,
SSHConfigUtil.remoteHost,SSHConfig.PORT);
//密码认证
jschSession.setPassword(SSHConfigUtil.passWord);
//SSH授权客户端位置,测试环境设置免授权,生产环境可对应服务器授权
//jsch.setKnownHosts(SSHConfig.SSH_PATH);
Properties config = new Properties();
config.put("StrictHostKeyChecking","no");
jschSession.setConfig(config);
//创建连接
jschSession.connect(SSHConfig.SESSION_TIMEOUT);
//建立可执行管道
ChannelExec channelExec = (ChannelExec) jschSession.openChannel("exec");
//执行脚本
channelExec.setCommand(shellScript);
//获取执行脚本可能出现的错误日志
channelExec.setErrStream(System.err);
//执行脚本输出结果
in = channelExec.getInputStream();
//设置超时时间
channelExec.connect(SSHConfig.CHANEL_TIME);
byte[] tmp = new byte[1024];
while(true){
while(in.available() > 0){
int i = in.read(tmp,0,1024);
if(i < 0) break;
log.info("脚本执行过程:"+new String(tmp,0,i));
}
//获取执行结果
if(channelExec.isClosed()){
if(in.available() > 0) continue;
if(channelExec.getExitStatus() != 0){
//脚本非正常结束,退出吗非零
flag = false;
log.info("脚本执行出错");
}
break;
}
try{
Thread.sleep(1000);
}catch (Exception e){
log.info(e.getMessage());
}
}
channelExec.disconnect();
}catch(Exception e){
log.info("执行脚本出错");
flag = false;
}finally {
if(jschSession != null) jschSession.disconnect();
}
return flag;
}
}
依赖信息
<dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> </dependency>