情景:要通过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, "未获取到数据,请再次调用");
}
}
}