1. 程式人生 > >java實現 連線遠端伺服器 執行Linux命令 並獲取 執行返回的結果

java實現 連線遠端伺服器 執行Linux命令 並獲取 執行返回的結果

情景:要通過java連線伺服器,並執行指令碼命令 得到 返回的結果

package com.ideal.openapi.util;

import com.jcraft.jsch.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.*;
import java.util.*;

/**
 * Created by joe強 on 2018/10/23 14:58
 */
public class SshServerUtils {
    private static final Logger lg = LoggerFactory.getLogger(SshServerUtils.class);
    private static Session session;

    //連線伺服器
    private static void connect(String username, String passwd, String host, int port) {
        try {
            JSch jsch = new JSch();
            //獲取sshSession
            session = jsch.getSession(username, host, port);
            //新增密碼
            session.setPassword(passwd);
            Properties sshConfig = new Properties();
            //嚴格主機金鑰檢查
            sshConfig.put("StrictHostKeyChecking", "no");
            session.setConfig(sshConfig);
            //開啟sshSession連線
            session.connect();
            lg.info("Server connection successful.");
        } catch (JSchException e) {
            e.printStackTrace();
        }
    }

    //執行相關命令
    public static String execCmd(String command, String username, String passwd, String host, int port, String outFilePath) {

        String resultJson = null;
        ChannelExec channelExec = null;
        if (command != null) {
            try {
                connect(username, passwd, host, port);
                channelExec = (ChannelExec) session.openChannel("exec");
                // 設定需要執行的shell命令
                channelExec.setCommand(command);
                lg.info("linux命令:" + command);
                channelExec.setInputStream(null);
                channelExec.setErrStream(System.err);
                channelExec.connect();
                //讀資料
                resultJson = getServerData(host, port, username, passwd, outFilePath);
            } catch (JSchException e) {
                e.printStackTrace();
            } finally {
                if (null != channelExec) {
                    channelExec.disconnect();
                }
            }
        }
        return resultJson;
    }

    // 從 伺服器 獲取 資料
    private static String getServerData(String host, int port, String username,
                                        String password, String filePath) {

        ChannelSftp sftp = null;
        StringBuffer buffer = new StringBuffer();
        try {

            if (!session.isConnected()) {
                connect(username, password, host, port);
            }

            //獲取sftp通道
            Channel channel = session.openChannel("sftp");
            //開啟
            channel.connect();
            sftp = (ChannelSftp) channel;
            lg.info("Connected to " + host + ".");
            //獲取生成檔案流
            InputStream inputStream = sftp.get(filePath);
            BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
            String line = "";
            while ((line = in.readLine()) != null) {
                buffer.append(line);
            }
            //關閉流
            inputStream.close();
            in.close();

            lg.info(" 執行結果為: " + buffer.toString());

        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSchException e) {
            e.printStackTrace();
        } catch (SftpException e) {
            e.printStackTrace();
        } finally {
            if (null != sftp) {
                sftp.quit();
            }
            closeSession();
        }
        return buffer.toString();
    }


    public static void closeSession() {
        if (session != null) {
            session.disconnect();
        }

    }

    public static String getUUID() {
        UUID uuid = UUID.randomUUID();
        String str = uuid.toString();
        return str.replace("-", "");
    }



}
package com.ideal.openapi.controller.python;


import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.ideal.openapi.dto.ResponseModel;
import com.ideal.openapi.entity.OData;
import com.ideal.openapi.entity.OMeta;
import com.ideal.openapi.enumerate.ResponseCode;
import com.ideal.openapi.util.SshServerUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;
import java.util.List;


/**
 * Created by joe強 on 2018/10/23 17:08
 */
@RestController
@PropertySource("classpath:server.properties")
public class PythonController {
    @Autowired
    ObjectMapper objectMapper;
    @Value("${server.host}")
    private String host;
    @Value("${server.thisport}")
    private int port;
    @Value("${server.username}")
    private String username;
    @Value("${server.password}")
    private String password;

    /**
     * filePath 指令碼絕對路徑
     *
     * @param request
     * @param
     * @throws IOException
     */
    @RequestMapping(value = "/executeCommand", method = RequestMethod.POST)
    public ResponseModel getDate(HttpServletRequest request) {
        String ruseltJson = null;
        //動態獲取引數
        Enumeration<String> parameterNames = request.getParameterNames();
        String filePath = request.getParameter("filePath");
        if (StringUtils.isEmpty(filePath)) {
            return ResponseModel.error(ResponseCode.INVALID_PARAMETER, "filePath 不能為空");
        }
        String params = new String();
        while (parameterNames.hasMoreElements()) {
            String name = (String) parameterNames.nextElement();
            if (!name.equals("filePath")) {
                String value = request.getParameter(name);
                params += name + "=" + value + " ";
            }
        }
        params = params.substring(0, params.length() - 1);
        String outFilePath = filePath + "/" + SshServerUtils.getUUID();

        // 拼接Liunx命令
        String command = String.format("cd %s && python gp.py search_grid_by_latlng %s > %s ", filePath, params, outFilePath);

        ruseltJson = SshServerUtils.execCmd(command, username, password, host, port, outFilePath);
        List data = null;
        if (!StringUtils.isEmpty(ruseltJson)) {
            try {
                //設定objectMapper識別單引號
                objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
                //json字串轉換為物件
                OData oData = objectMapper.readValue(ruseltJson, OData.class);
                data = oData.getData();
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return ResponseModel.success(data);
        } else {
            return ResponseModel.error(ResponseCode.SYS_ERROR, "未獲取到資料,請再次呼叫");


        }

    }


}