`
落叶换新叶
  • 浏览: 24520 次
  • 性别: Icon_minigender_1
社区版块
存档分类
最新评论

ethz.ssh2 本地操作linux服务器

阅读更多

 1.调用代码

  

import ch.ethz.ssh2.*;
import java.io.*;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;

public class RemotShellTool {
    public static void main(String[] args) throws Exception {
        // 上传文件
        RemotShellTool.updateFile();
        // 修改文件权限
        RemotShellTool.chmodFile();
        // 打包
       RemotShellTool.pack("D:\\dev\\workspace\\taiping-dianshang-core-release2");
        // 运行项目
       RemotShellTool.execCommond();
    }

    // 打包
    public static void pack(String path) {
        try {
            Process process = Runtime.getRuntime().exec("cmd /c  mvn install -Dmaven.test.skip=true ");

            new Thread(new ThreadStream(process.getErrorStream())).start();
            new Thread(new ThreadStream(process.getInputStream())).start();

            process.waitFor();
            process.destroy();
            process.getOutputStream().close();
            process.getErrorStream().close();
            process.getInputStream().close();

        }catch (Exception e) {
            e.printStackTrace();
        }
    }
    // 执行命令
    public static void execCommond() throws Exception {
        String fileName = "taiping-jinfu-task-20191009102720.jar";
        String port = "8888";
        Connection connection = new Connection("ip");
        connection.connect();//连接
        connection.authenticateWithPassword("username","password");//认证
        Session session=connection.openSession();
        session.execCommand("cd /home/loginuser && sh test.sh "+fileName+" "+port);
        InputStream is = new StreamGobbler(session.getStdout());//获得标准输出流
        BufferedReader brs = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
        String temp = "";
        while ((temp=brs.readLine()) != null) {
            System.out.println(temp);
        }
        InputStream errStream = new StreamGobbler(session.getStderr());
        BufferedReader errReader = new BufferedReader(new InputStreamReader(errStream,Charset.forName("UTF-8")));
        String errTemp = "";
        while((errTemp=errReader.readLine()) !=null) {
            int i=1;
            System.out.println(errTemp);
        }

      //  new Thread(new ThreadStream(session.getStdout())).start();
        if (session != null) {
            session.close();
        }
        session.close();
        brs.close();
       // errReader.close();
        connection.close();
    }
    // 修改文件权限
    public static void chmodFile() throws Exception {
        String fileName = "taiping-jinfu-task-20191009102720.jar";
        Connection connection = new Connection("ip");
        connection.connect();//连接
        connection.authenticateWithPassword("username","password");//认证
        Session session=connection.openSession();
        session.execCommand("chmod 664 /home/loginuser/"+fileName);

        if (session != null) {
            session.close();
        }
        session.close();
    }

   public static void updateFile() throws Exception{
        Connection connection = new Connection("ip");
        connection.connect();//连接
        connection.authenticateWithPassword("username","password");//认证

        SCPClient scpClient = connection.createSCPClient();
        String localFilePath = "D:\\tpdata\\upload\\taiping-jinfu-task-0.0.1-SNAPSHOT.jar";
        File localFile = new File(localFilePath);

        String remoteFilePath = "/home/loginuser/";
        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String remoteFileName = "taiping-jinfu-task-"+timeStamp+".jar";
        SCPOutputStream os= scpClient.put(remoteFileName,localFile.length(),remoteFilePath,"0222");

        byte[] b = new byte[4096];
        FileInputStream fis = new FileInputStream(localFile);
        int i;
        while ((i = fis.read(b)) != -1) {
            os.write(b, 0, i);
        }
        os.flush();
        fis.close();
        os.close();

    }
}

 

 

2.引用maven,版本使用262的,使用较低的版本,api会不一样

 

<dependency>
            <groupId>ch.ethz.ganymed</groupId>
            <artifactId>ganymed-ssh2</artifactId>
            <version>262</version>
</dependency>

 

 3.test.sh脚本

 #!/bin/bash
export JAVA_HOME=/home/loginuser/jdk
export JRE_HOME=/home/loginuser/jdk/jre
export PATH=/usr/local/bin:/usr/local/lib:$JAVA_HOME/bin:$PATH
export CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar:$JAVA_HOME/jre/lib

PID=$(netstat -anp|grep $2|awk '{printf $7;exit;}'|cut -d/ -f1)
echo 'PID:'$PID
if [$PID = ""];
then
  echo '没有端口占用'
else
  echo 'kill 占用端口'
  kill -9 $PID
fi
nohup java -jar $1 -Dserver.port=$2 > nohup.out
tail -200f  nohup.out

 

 4.操作日志线程类

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ThreadStream implements  Runnable {

    private InputStream inputStream;

    public ThreadStream(InputStream inputStream) {
        this.inputStream=inputStream;
    }
    @Override
    public void run() {

        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"GBK"));
            String s = "";
            while((s = bufferedReader.readLine())!=null) {
                System.out.println("输出结果:"+s);
            }
            bufferedReader.close();

            System.out.println("输出结果:"+s);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

 

 

 

 

2
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics