- java 程序远程linux服务器有两个框架分别是:jsch与ganymed-ssh2框架。
- 目前ganymed-ssh框架不维护了,同时不支持openssl的版本
- 下篇更新jsch的文章
一、导入相关依赖包
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>262</version>
</dependency>
二、实现相关的工具类
/**
* 远程获取execl文件的工具类
*/@Component
public class ScpClientUtil {
//日志记录工具
private static final Logger logger = LoggerFactory.getLogger(ScpClientUtil.class);
//远程ip
private static String ip;
//远程用户名
private static String userName;
//远程密码
private static String password;
//连接的端口
private static int port;
//设置编码格式
private static String charset;
@Value("${auth.ip}")
public void setIp(String ip) {
this.ip = ip;
}
@Value("${auth.userName}")
public void setUserName(String userName) {
this.userName = userName;
}
@Value("${auth.password}")
public void setPassword(String password) {
this.password = password;
}
@Value("${auth.port}")
public void setPort(String port) {
this.port = Integer.valueOf(port);
}
@Value("${ File .charset}")
public void setEncoding(String charset) {
this.charset=charset;
}
/** 获取连接 */public static Connection getConnect(String hostName, String username, String password, int port ) {
Connection conn = new Connection(hostName, port);
try {
// 连接到主机
conn.connect();
// 使用用户名和密码校验
boolean isconn = conn.authenticateWithPassword(username, password);
if (!isconn) {
conn=null;
logger.info("用户名称或者是密码不正确");
} else {
logger.info("服务器连接成功.");
return conn;
}
} catch ( Exception e) {
conn=null;
e.printStackTrace();
}
return conn;
}
/**
* 读取文件内容
*/public static void getFileContent(Connection conn, String remotePath){
BufferedReader bufferedReader=null;
try {
SFTPv3Client sft = new SFTPv3Client(conn);
// 设置编码格式,可以获取到中文文件
sft.setCharset("GBk");
List<SFTPv3DirectoryEntry> list = sft.ls(remotePath);
SCPClient scpClient = conn.createSCPClient();
scpClient.setCharset("GBK");
String line;
for (int i = 0; i < list.size(); i++) {
String mkdir=list.get(i).filename;
//不允许访问根目录
if(!mkdir.startsWith("."))
{
List<SFTPv3DirectoryEntry> mkdirFiles = sft.ls(remotePath+mkdir+"/");
for(int k=0;k<mkdirFiles.size();k++){
//获取相关的文件名
String fileName=mkdirFiles.get(i).filename;
String localPath="---要读取的路径---"+fileName;
SCPInputStream in = scpClient.get(localPath.replace("\", "//"));
bufferedReader = new BufferedReader(new InputStream Reader(in,ScpClientUtil.charset));
while((line=bufferedReader.readLine())!=null) {
//---------------------
//要执行的业务代码块
//---------------------
System.out.println(line);
}
}
}
}
}catch (Exception e) {
e.printStackTrace();
}finally {
if(bufferedReader!=null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/***创建连接服务器*/public static Connection createConection() {
//不同平台存放数据
Connection conn = getConnect(ip, userName, password, port);
logger.info(ip);
logger.info(userName);
logger.info(password);
logger.info(String.valueOf(port));
return conn;
}
}