添加远程连接服务器依赖。
<!-- 远程连接服务器-->
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>build210</version>
</dependency>
部署服务器上使用直接连接使用,单条命令执行,返回执行后的结果
/**(部署服务器上使用)
* 单条命令执行,返回执行后的结果
* command可拼接多条命令
* @param command 输入的命令
* @return 执行结果
*/
public static String executeOneCommand(String command) {
//String finalCommand = command;
String[] finalCommand = new String[]{"/bin/sh","-c",command};
StringBuilder stringBuilder = new StringBuilder();
try {
Process process = Runtime.getRuntime().exec(finalCommand);
process.waitFor();
//读取屏幕输出
BufferedReader strCon = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = strCon.readLine()) != null) {
stringBuilder.append(line + "\n");
}
System.out.println("stringBuilder===>"+stringBuilder);
} catch (Exception e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
本地代码端连接服务器使用。
/**
* 获得连接(本地连接服务器直接使用)
* @param ip
* @param userName
* @param pwd
* @param port
* @return
*/
public static Connection getConn(String ip, String userName, String pwd, int port){
Connection conn = new Connection(ip,port);
boolean blag = false;
try {
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(userName, pwd);
//session = conn.openSession();
//client = new SCPClient(conn);
if (isAuthenticated) {
blag = true;
}
if (isAuthenticated == false) {
throw new IOException("Authentication failed.文件scp到数据服务器时发生异常");
}
} catch (IOException e) {
e.printStackTrace();
}
if (blag) {
return conn;
}else {
return null;
}
}
public static String parseResult(InputStream inputStream) throws IOException{
//读取输出流内容
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,DEFAULT_CHARSET));
StringBuffer resultSB = new StringBuffer();
String line;
while((line = br.readLine()) != null){
resultSB.append(line + "\n");
}
//替换换行符
//String result = resultSB.toString().replaceAll("[\\t\\n\\r]", "");
return resultSB.toString();
}
/**
* 执行命令(本地连接服务器直接使用,测试使用)
* @param command 命令语句
* @return 执行结果
*/
public static String execCommand(String command){
String dataServerIp = "192.168.12.xxx";//服务器IP
String dataServerUsername = "root";//服务器用户名
String dataServerPassword = "xxxxx";//服务器登录密码
Integer port = 22;//端口号
Connection connection = getConn(dataServerIp, dataServerUsername, dataServerPassword, port);
Session session = null;
String result = "";
try{
session = connection.openSession();
//执行命令
session.execCommand(command);
//解析结果
result = parseResult(session.getStdout());
//解析结果为空,则表示执行命令发生了错误,尝试解析错误处输出
if (result == null || result.length() == 0){
result = parseResult(session.getStderr());
System.out.println("result===>"+result);
}else {
System.out.println("result===>"+result);
return result;
}
}catch (Exception e){
e.printStackTrace();
}
return result;
}