SSH连接服务器
Posted 枫沫
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SSH连接服务器相关的知识,希望对你有一定的参考价值。
package com.fastech.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.log4j.Logger;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
public class SSHconnector {
public static final Logger log = Logger.getLogger(SSHconnector.class);
private Connection connection;
private Session session = null;
private static final int TIME_OUT = 30 * 1000;
/**
* 连接服务器
* */
public boolean connect(String ip,int port) {
connection = new Connection(ip,port);//获取连接
try {
//connection
connection.connect(null, TIME_OUT, TIME_OUT);
} catch (IOException e) {
e.printStackTrace();
log.info("->SSHConnection connect failure: "+e);
return false;
}
log.info("Connect "+ip+":"+port+" Success!");
return true;
}
/**
* 执行命令
* */
public String sender(String command) {
try {
session = connection.openSession();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
StringBuffer sb = new StringBuffer();
InputStream inputstream = null;
InputStream inputstreamError = null;
BufferedReader br = null;
BufferedReader brError = null;
try {
session.execCommand(command);
inputstream = new StreamGobbler(session.getStdout());
inputstreamError = new StreamGobbler(session.getStderr());
br = new BufferedReader(new InputStreamReader(inputstream,"utf-8"));
brError = new BufferedReader(new InputStreamReader(inputstreamError,"utf-8"));
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
boolean errorFlag = false;
while ((line = brError.readLine()) != null) {
if (!errorFlag) sb.append("Result:8 ");
sb.append(line + ";\n");
errorFlag = true;
}
} catch (IOException e) {
log.info("->SSHConnection send command failure: "+e);
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
if (brError != null) {
brError.close();
}
if (inputstream != null) {
inputstream.close();
}
if (inputstreamError != null) {
inputstreamError.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
if (sb.toString() != null && !"".equals(sb.toString())) {
String result = sb.substring(0, sb.length() - 1);
if (!result.contains("Result:")) {
return "Result:4 " + result + ";";
}
return result;//截取最后一个\n;
}
return null;
}
/**
* 关闭连接
* */
public void destory() {
if (session != null) {
session.close();
}
if (connection != null) {
connection.close();
}
}
/**
* 登录服务器
* */
public Boolean login(String username,String password) {
try {
boolean isAuthenticate = connection.authenticateWithPassword(username,password);
if (!isAuthenticate) {
log.info("->SSHConnection login failure: ");
}
} catch (Exception e) {
log.info("->SSHConnection login failure: "+e);
e.printStackTrace();
return false;
}
return true;
}
}
以上是关于SSH连接服务器的主要内容,如果未能解决你的问题,请参考以下文章