使用纯java ssh方式连接linux服务器,并用此方式部署war到linux的tomcat下

[b]纯java代码使用ssh方式登录linux服务。
实际应用中,可以使用这种方式上传部署web工程war包 并且部署启动tomcat 一个自动化完成所有工作 起到节省时间作用。

1.去[url=http://www.jcraft.com/jsch/]官网[/url]下载最新的jar包
jsch-0.1.51.jar
[/b]

下面是我的java code 例子



/**
* java ssh登录linux以后的一些操作方式
* @author liuxy
*
*/
public class SchUnitJsch extends SchUnit{
private final static Log logger =LogFactory.getLog(SchUnitJsch.class);
public SchUnitJsch() {
super();
}


public SchUnitJsch(String username, String password, String host) {
super(username, password, host);
}
/**
* 开启session
* @return
* @throws JSchException
*/
private Session openSession() throws JSchException{
JSch jsch=new JSch();
Session session=null;
session=jsch.getSession(username, host);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
session.setConfig(sshConfig);
session.setPassword(password);
session.connect(3000);
return session;
}
/**
* 上传本地文件到远程linux上
* 使用sftp上传
*/
@Override
public boolean uploadLocalFileToRemote(String localFile, String remoteDir) {
Session session=null;
try {
session = openSession();
} catch (JSchException e) {
logger.error(e.getMessage());
if(session!=null) session.disconnect();
return false;
}
ChannelSftp channel=null;
try {
channel=(ChannelSftp) session.openChannel("sftp");
channel.connect();
SftpProgressMonitorImpl sftpProgressMonitorImpl=new SftpProgressMonitorImpl();
channel.put(localFile, remoteDir,sftpProgressMonitorImpl);

return sftpProgressMonitorImpl.isSuccess();
}catch (JSchException e) {
if(channel!=null){
channel.disconnect();
session.disconnect();
}
return false;
} catch (SftpException e) {
logger.error(e.getMessage());
}
return false;
}
/**
* 上传镜像映射检测
* @author liuxy
*
*/
static class SftpProgressMonitorImpl implements SftpProgressMonitor{
private long size;
private long currentSize=0;
private boolean endFlag=false;
@Override
public void init(int op, String srcFile, String dstDir, long size) {
logger.debug("文件开始上传:【"+srcFile+"】-->【"+dstDir+"】"+",文件大小:"+size+",参数"+op);
this.size=size;
}

@Override
public void end() {
logger.debug("文件上传结束");
endFlag=true;
}

@Override
public boolean count(long count){
currentSize+=count;
logger.debug("上传数量:"+currentSize);
return true;
}
public boolean isSuccess(){
return endFlag&¤tSize==size;
}
}

/**
* 执行指令
* @param commands
*/
public StringBuffer executeCommands(String commands){
return executeCmd(commands).getOutRes();
}
/**
* 执行shell指令并且返回结果对象ResInfo
* @param commands
* @return
*/
public ResInfo executeCmd(String commands){
ResInfo resInfo=new ResInfo();
Session session=null;
try {
session = openSession();
} catch (JSchException e) {
logger.debug(e.getMessage());
if(session!=null) session.disconnect();
return null;
}
ChannelExec channel=null;
StringBuffer result=new StringBuffer();
StringBuffer errResult=new StringBuffer();
try {
channel=(ChannelExec) session.openChannel("exec");
channel.setCommand(commands);
channel.setInputStream(null);
((ChannelExec)channel).setErrStream(null);
InputStream in=channel.getInputStream();
InputStream err=channel.getErrStream();
channel.connect();
byte[] bytes=new byte[1024];
byte[] bytesErr=new byte[1024];
while(true){
while(in.available()>0){
int i=in.read(bytes, 0, 1024);
if(i0){
int i=err.read(bytesErr, 0, 1024);
if(i0||err.available()>0) continue;
logger.debug("exit-status: "+channel.getExitStatus());
resInfo.setExitStuts(channel.getExitStatus());
resInfo.setOutRes(result);
resInfo.setErrRes(errResult);
break;
}
Thread.sleep(1000);
}
return resInfo;
} catch (JSchException e) {
logger.error(e.getMessage());
return null;
} catch (Exception e) {
logger.error(e.getMessage());
return null;
}finally{
channel.disconnect();
session.disconnect();
}
}

//exec command 结果返回对象
public static class ResInfo{
int exitStuts;//返回状态码 (在linux中可以通过 echo $? 可知每步执行令执行的状态码)
StringBuffer outRes;//标准正确输出流内容
StringBuffer errRes;//标准错误输出流内容
public int getExitStuts() {
return exitStuts;
}
public void setExitStuts(int exitStuts) {
this.exitStuts = exitStuts;
}
public StringBuffer getOutRes() {
return outRes;
}
public void setOutRes(StringBuffer outRes) {
this.outRes = outRes;
}
public StringBuffer getErrRes() {
return errRes;
}
public void setErrRes(StringBuffer errRes) {
this.errRes = errRes;
}

public void clear(){
exitStuts=0;
outRes=errRes=null;
}
}



public static abstract class MyUserInfo
implements UserInfo, UIKeyboardInteractive{
@Override
public String getPassword(){ return null; }
@Override
public boolean promptYesNo(String str){ return false; }
@Override
public String getPassphrase(){ return null; }
@Override
public boolean promptPassphrase(String message){ return false; }
@Override
public boolean promptPassword(String message){ return false; }
@Override
public void showMessage(String message){ }
@Override
public String[] promptKeyboardInteractive(String destination,
String name, String instruction, String[] prompt, boolean[] echo) {
return null;
}
}
/**
* 删除远程linux下的文件
*/
@Override
public boolean deleteRemoteFileorDir(String remoteFile) {
Session session=null;
try {
session = openSession();
} catch (JSchException e) {
logger.info(e.getMessage());
if(session!=null) session.disconnect();
return false;
}
ChannelSftp channel=null;
try {
channel=(ChannelSftp) session.openChannel("sftp");
channel.connect();
SftpATTRS sftpATTRS= channel.lstat(remoteFile);
if(sftpATTRS.isDir()){
//目录
logger.debug("remote File:dir");
channel.rmdir(remoteFile);
return true;
}else if(sftpATTRS.isReg()){
//文件
logger.debug("remote File:file");
channel.rm(remoteFile);
return true;
}else{
logger.debug("remote File:unkown");
return false;
}
}catch (JSchException e) {
if(channel!=null){
channel.disconnect();
session.disconnect();
}
return false;
} catch (SftpException e) {
logger.error(e.getMessage());
}
return false;
}
/**
* 判断linux下 某文件是否存在
*/
@Override
public boolean detectedFileExist(String remoteFile) {
Session session=null;
try {
session = openSession();
} catch (JSchException e) {
logger.info(e.getMessage());
if(session!=null) session.disconnect();
return false;
}
ChannelSftp channel=null;
try {
channel=(ChannelSftp) session.openChannel("sftp");
channel.connect();
SftpATTRS sftpATTRS= channel.lstat(remoteFile);
if(sftpATTRS.isDir()||sftpATTRS.isReg()){
//目录 和文件
logger.info("remote File:dir");
return true;
}else{
logger.info("remote File:unkown");
return false;
}
}catch (JSchException e) {
if(channel!=null){
channel.disconnect();
session.disconnect();
}
return false;
} catch (SftpException e) {
logger.error(e.getMessage());
}
return false;
}


}



将web工程的war部署到tomcat下的



/**
* 将war包部署到linux的tomcat下一些操作方法
* @author liuxy
*
*/
public class DetectedTomcatService extends BaseService{
private final static Log logger=LogFactory.getLog(DetectedTomcatService.class);
//tomcat所在的linux下的根目录
public String baseTomcatHome;
public DetectedTomcatService(String username, String pwd, String host) {
super(username, pwd, host);
}
/**
* 检测tomcat是否启动
*/
public boolean isStartingTomcat(String command){
if(command==null)command="ps -ef | grep Tomcat | grep -v grep";
StringBuffer res=sshUnit.executeCommands(command);
logger.debug(res);
return !StringUtils.isBlank(res);

}
/**
* 关闭tomcat
*/
public boolean shutdownTomcat(String commandShutdownTomcat){

String command="ps -ef | grep Tomcat | grep -v grep";
if(isStartingTomcat(command)){
if(StringUtils.isBlank(commandShutdownTomcat)){
StringBuffer res=sshUnit.executeCommands(command);
String[] fragments=res.toString().split("\\s+");
for(String fragment:fragments){
logger.debug(fragment);
if(fragment.indexOf("catalina.base")>-1||fragment.indexOf("catalina.base")>-1)
{
baseTomcatHome=fragment.split("=")[1];
break;
}
continue;
}
logger.info("baseTomcatHome:"+baseTomcatHome);
if(baseTomcatHome!=null) commandShutdownTomcat="sh "+baseTomcatHome+"/bin/shutdown.sh";
}
//关闭tomcat
sshUnit.executeCommands(commandShutdownTomcat);
//等待几秒钟
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
logger.equals(e.getMessage());
}
boolean success=isStartingTomcat(command);
if(success){
StringBuffer res=sshUnit.executeCommands(command);
String[] fragments=res.toString().split("\\s+");
sshUnit.executeCommands("kill -9 "+fragments[1]);
}
return true;
}
return true;
}
/**
* 开启tomcat
*/
public void startupTomcat(String commandStartupTomcat){
String command="ps -ef | grep Tomcat | grep -v grep";
if(isStartingTomcat(command)){
shutdownTomcat(null);
}
//开启tomcat
if(StringUtils.isBlank(commandStartupTomcat))
commandStartupTomcat="sh "+baseTomcatHome+"/bin/startup.sh";
sshUnit.executeCommands(commandStartupTomcat);
}
/**
* 删除war包
* @return
*/
public boolean deleteWar(){
String regex=baseTomcatHome+"/webapps/ROOT*";
String deleteCommand="rm -rf "+ regex;
String detectFileCommand="ls "+baseTomcatHome+"/webapps | grep ROOT";
String commands=deleteCommand+" ; "+detectFileCommand;
StringBuffer res=sshUnit.executeCommands(commands);
return StringUtils.isBlank(res);
}
/**
* 上传war包
* @param baseTomcatHome
*/
public boolean uploadWar(String localFile){
String remoteDir=baseTomcatHome+"/webapps";
sshUnit.uploadLocalFileToRemote(localFile,remoteDir);
return sshUnit.uploadLocalFileToRemote(localFile,remoteDir);
}

public boolean warDealwith(){
String commands="cd "+baseTomcatHome+"/webapps;mv ROOT.war ROOT.zip;unzip ROOT.zip -d ROOT;rm -rf ROOT.zip";
StringBuffer res=sshUnit.executeCommands(commands);
logger.info(res);
return !StringUtils.isBlank(res);
}


public void setBaseTomcatHome(String baseTomcatHome) {
this.baseTomcatHome = baseTomcatHome;
}


}


测试war包上传例子

/**
* 将演示主程序
* @author liuxy
*
*/
public class TomcatPublish{
private static final Log logger =LogFactory.getLog(TomcatPublish.class);
private DetectedTomcatService tomcatService;
private String baseTomcatHome="/opt/server/Tomcat";//设置默认tomcat根目录
private String localFileWarPath;//本地war包路径
public TomcatPublish(String username,String pwd,String host){
tomcatService=new DetectedTomcatService(username, pwd, host);
tomcatService.setBaseTomcatHome(baseTomcatHome);
}
public void publish(){
//关闭tomcat
boolean success=tomcatService.shutdownTomcat(null);

if(!success){
logger.debug("Tomcat shutdown failed"); return ;
}
//删除原有文件
success=tomcatService.deleteWar();
if(!success){
logger.debug("ROOT 残留war包已经文件没有删除干净");
return ;
}
//上传文件
if(tomcatService.uploadWar(localFileWarPath)){
//解压
logger.debug("=============================================解压缩====================");
if(tomcatService.warDealwith()){
logger.debug("........start Tomcat......");
tomcatService.startupTomcat(null);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {

}
System.exit(0);
}

}
else
logger.debug("上传失败war");

}
public DetectedTomcatService getTomcatService() {
return tomcatService;
}
public void setTomcatService(DetectedTomcatService tomcatService) {
this.tomcatService = tomcatService;
}
public String getBaseTomcatHome() {
return baseTomcatHome;
}
public void setBaseTomcatHome(String baseTomcatHome) {
this.baseTomcatHome = baseTomcatHome;
}
public String getLocalFileWarPath() {
return localFileWarPath;
}
public void setLocalFileWarPath(String localFileWarPath) {
this.localFileWarPath = localFileWarPath;
}
public static void main(String[] args) {
TomcatPublish tomcatPublish=new TomcatPublish("登录用户名(如root)","密码","主机域名(如:192.168.0.123)");
tomcatPublish.setLocalFileWarPath("E:\\WarFiles\\ROOT.war");
TomcatPublish tomcatPublish=new tomcatPublish.publish();
}
}

你可能感兴趣的:(java,应用技术)