Java远程连接Linux服务器并执行命令及上传文件功能
作者:StaticKing 发布时间:2023-01-28 14:03:31
标签:java,linux,服务器,上传文件
最近再开发中遇到需要将文件上传到Linux服务器上,至此整理代码笔记。
此种连接方法中有考虑到并发问题,在进行创建FTP连接的时候将每一个连接对象存放至
ThreadLocal<Ftp> 中以确保每个线程之间对FTP的打开与关闭互不影响。
package com.test.utils;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class Ftp {
//打印log日志
private static final Log logger = LogFactory.getLog(Ftp.class);
private static Date last_push_date = null;
private Session sshSession;
private ChannelSftp channel;
private static ThreadLocal<Ftp> sftpLocal = new ThreadLocal<Ftp>();
private Ftp(String host, int port, String username, String password) throws Exception {
JSch jsch = new JSch();
jsch.getSession(username, host, port);
//根据用户名,密码,端口号获取session
sshSession = jsch.getSession(username, host, port);
sshSession.setPassword(password);
//修改服务器/etc/ssh/sshd_config 中 GSSAPIAuthentication的值yes为no,解决用户不能远程登录
sshSession.setConfig("userauth.gssapi-with-mic", "no");
//为session对象设置properties,第一次访问服务器时不用输入yes
sshSession.setConfig("StrictHostKeyChecking", "no");
sshSession.connect();
//获取sftp通道
channel = (ChannelSftp)sshSession.openChannel("sftp");
channel.connect();
logger.info("连接ftp成功!" + sshSession);
}
/**
* 是否已连接
*
* @return
*/
private boolean isConnected() {
return null != channel && channel.isConnected();
}
/**
* 获取本地线程存储的sftp客户端
*
* @return
* @throws Exception
*/
public static Ftp getSftpUtil(String host, int port, String username, String password) throws Exception {
//获取本地线程
Ftp sftpUtil = sftpLocal.get();
if (null == sftpUtil || !sftpUtil.isConnected()) {
//将新连接防止本地线程,实现并发处理
sftpLocal.set(new Ftp(host, port, username, password));
}
return sftpLocal.get();
}
/**
* 释放本地线程存储的sftp客户端
*/
public static void release() {
if (null != sftpLocal.get()) {
sftpLocal.get().closeChannel();
logger.info("关闭连接" + sftpLocal.get().sshSession);
sftpLocal.set(null);
}
}
/**
* 关闭通道
*
* @throws Exception
*/
public void closeChannel() {
if (null != channel) {
try {
channel.disconnect();
} catch (Exception e) {
logger.error("关闭SFTP通道发生异常:", e);
}
}
if (null != sshSession) {
try {
sshSession.disconnect();
} catch (Exception e) {
logger.error("SFTP关闭 session异常:", e);
}
}
}
/**
* @param directory 上传ftp的目录
* @param uploadFile 本地文件目录
*
*/
public void upload(String directory, String uploadFile) throws Exception {
try {<br> //执行列表展示ls 命令
channel.ls(directory);<br> //执行盘符切换cd 命令
channel.cd(directory);
List<File> files = getFiles(uploadFile, new ArrayList<File>());
for (int i = 0; i < files.size(); i++) {
File file = files.get(i);
InputStream input = new BufferedInputStream(new FileInputStream(file));
channel.put(input, file.getName());
try {
if (input != null) input.close();
} catch (Exception e) {
e.printStackTrace();
logger.error(file.getName() + "关闭文件时.....异常!" + e.getMessage());
}
if (file.exists()) {
boolean b = file.delete();
logger.info(file.getName() + "文件上传完毕!删除标识:" + b);
}
}
}catch (Exception e) {
logger.error("【子目录创建中】:",e);
//创建子目录
channel.mkdir(directory);
}
}
//获取文件
public List<File> getFiles(String realpath, List<File> files) {
File realFile = new File(realpath);
if (realFile.isDirectory()) {
File[] subfiles = realFile.listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
if (null == last_push_date ) {
return true;
} else {
long modifyDate = file.lastModified();
return modifyDate > last_push_date.getTime();
}
}
});
for (File file : subfiles) {
if (file.isDirectory()) {
getFiles(file.getAbsolutePath(), files);
} else {
files.add(file);
}
if (null == last_push_date) {
last_push_date = new Date(file.lastModified());
} else {
long modifyDate = file.lastModified();
if (modifyDate > last_push_date.getTime()) {
last_push_date = new Date(modifyDate);
}
}
}
}
return files;
}
}
总结
以上所述是小编给大家介绍的Java远程连接Linux服务器并执行命令及上传文件,希望对大家有所帮助如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!
来源:https://www.cnblogs.com/staticking/p/9082648.html


猜你喜欢
- 本文实例为大家分享了C#获取计算机信息的具体代码,供大家参考,具体内容如下using System;using System.Configu
- 本文实例为大家分享了android拖拽框,裁剪出图片的具体代码,供大家参考,具体内容如下import android.graphics.Bi
- session超时退到登录页面最近发现使用的工程居然没有session超时机制,功能太欠缺了,现在把追加方法分享出来,里面有一些坑,大家自由
- View绘制的三大流程,指的是measure(测量)、layout(布局)、draw(绘制) measure负责确定View的测量宽/高,也
- 快速排序实现: namespace QuickSort { class QuickSort { public static void Sor
- 本文实例为大家分享了C#遍历文件夹获取指定后缀名文件的具体代码,供大家参考,具体内容如下问题描述:项目需要,要进行某文件夹下所有shp数据的
- 上一篇文章我们了解了Java背包问题求解实例代码,接下来我们看看Java中模仿用户登录的相关代码,下面是具体内容。基于用户从控制台输入模拟的
- Android 自定义View实现抽屉效果说明这个自定义View,没有处理好多点触摸问题View跟着手指移动,没有采用传统的scrollBy
- 前言Docker旨在提供一种应用程序的自动化部署解决方案,在 Linux 系统上迅速创建一个容器(轻量级虚拟机)并部署和运行应用程序,并通过
- Java代码 mvn install:install-file -DgroupId=包名 -DartifactId=项目名 -Dversio
- 本文实例为大家分享了Spring boot实现文件上传的具体代码,供大家参考,具体内容如下1. 创建一个Maven的web工程,然后配置po
- namespace PadWebServices.Model{ public static class DataTa
- 在servlet中,转发和重定向是由request和response完成的。两者之间的区别请看我之前的文章。那么在springMVC中是如何
- 在第一次启动项目的时候,由于使用了RabbitMQ的默认guest账号,怎么也登不进去,后来还是在Admin重新创建了一个其他的账号,然后开
- 这篇文章主要介绍了Spring Boot Logback配置日志过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考
- 什么是Swagger?Swagger是什么:THE WORLD'S MOST POPULAR API TOOLING根据官网的介绍:
- 下载:DownLoaderTask.javapackage com.johnny.testzipanddownload;import jav
- 报错问题如图:仔细看报错问题后发现,这个错误的主要原因是:ValidatorException:PKIX path building fai
- 写在前面“The origin server did not find a current representation for the t
- 前言:学习了SpringBoot分页查询的两种写法,一种是手动实现,另一种是使用框架实现。现在我将具体的实现流程分享一下。首先是手动实现分页