最近再开发中遇到需要将文件上传到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 {
//执行列表展示ls 命令
channel.ls(directory);
//执行盘符切换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服务器并执行命令及上传文件的更多相关文章

  1. ssh远程连接linux服务器并执行命令

    详细方法: SSHClient中的方法 参数和参数说明 connect(实现ssh连接和校验) hostname:目标主机地址 port:主机端口 username:校验的用户名 password:登 ...

  2. Linux系统通过AWS命令行上传文件至S3

    打开你的AWS控制台: 在IAM中创建一个新用户(比如test),创建时它会自动创建一个用户安全凭证,是由“访问密钥ID”和“私有访问密钥”组成的,请记住它并下载该凭证,后面会用到它: 选择你刚创建的 ...

  3. python批量操作Linux服务器脚本,ssh密码登录(执行命令、上传、下载)(一)

     -*-          paramiko.util.log_to_file(         ssh = paramiko.SSHClient()          ssh.set_missing ...

  4. python批量操作Linux服务器脚本,key登录(执行命令、上传、下载)(二)

       -*-   2 #批量操作linux服务器(执行命令,上传,下载)   3 #!/usr/bin/python   4 import paramiko   5 import datetime   ...

  5. Sublime 远程连接 Linux服务器

    Sublime是一款强大的编辑器,它的强大体现在它强大的插件. 要实现Sublime 远程连接 Linux服务器,需要使用插件SFTP. 一. 插件安装 用Package Control安装插件按下C ...

  6. widows本地-xshell实现远程连接linux服务器图形界面

    本地环境远程连接linux图形界面,常用的实现工具有,VNC.Puty.Xshell等,这里我们用的xshell manager: Xmanager简介:Xmanager是一个运行于 Windows平 ...

  7. Window系统远程连接Linux服务器(非桌面系统)

    Window系统远程连接Linux服务器(非桌面系统) Window系统远程连接Linux服务器(非桌面系统),步骤: 第一步:下载Xshell远程登录软件:第二步:设置Linux服务器的IP.端口. ...

  8. widows终端远程连接Linux服务器

    一.前言 为什么不是远程连接Linux服务器? 因为我不会,远程连接window我就用电脑自带的“远程桌面连接”. 以下所述都是在CentOS操作系统下的. 服务器刚换成Linux的时候很迷茫,感觉无 ...

  9. vscode远程连接linux服务器,可视化绘图

    vscode远程连接linux服务器 想要实现的功能和解决方案 实现的功能: windows下直接使用远程linux服务器的python环境和文件来编写和运行py文件, 实时的编写py文件,和可视化绘 ...

随机推荐

  1. 014_go语言中的变参函数

    代码演示 package main import "fmt" func sum(nums ...int) { fmt.Print(nums, " ") toto ...

  2. 大学生可用来接单,利用Python实现教务系统扩容抢课!

    最近一学期一次的抢课大戏又来了,几家欢乐几家愁.O(∩_∩)O哈哈~(l我每次一选就过了hah,我还是有欧的时候滴).看着他们盯着教务系统就着急,何况我们那教务系统,不想说什么.emmm 想周围的朋友 ...

  3. 数电学习笔记之CMOS传输门工作原理

    CMOS 传输门从结构上看是由一个PMOS和一个NMOS管组成 先简单粗略讲讲PMOS管和NMOS管导通与截止吧 首先我们MOS管有三个极,源极(S:Source).漏极(D:Drain)和栅极(G: ...

  4. 发布新版首页“外婆新家”升级版:全新的UI,熟悉的味道

    在7月30日我们我们忐忑不安地发布了新版网站首页,发布后迎接我们的不是新颜新风貌的惊喜,而是我们最担心的残酷现实——“让我们等这么多年,等来的就是这个新的丑容颜”,在大家的批评声中我们深深地认识到我们 ...

  5. cudnn加速计算

    cudnn加速运算 torch.backends.cudnn.enabled = True torch.backends.cudnn.benchmark = True 第一句话是说,使用的是非确定性算 ...

  6. CSS 定位总结

    目录 元素显示模式 元素模式 元素显示模式转换 CSS定位机制 静态定位static 相对定位relative 绝对定位absolute 固定定位fixed 粘性定位sticky 定位小结一图流 CS ...

  7. GitHub上最火的SpringCloud微服务商城系统项目,附全套教程

    项目介绍 mall-swarm是一套微服务商城系统,采用了 Spring Cloud Greenwich.Spring Boot 2.MyBatis.Docker.Elasticsearch等核心技术 ...

  8. C#LeetCode刷题之#594-最长和谐子序列​​​​​​​​​​​​​​(Longest Harmonious Subsequence)

    问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3800 访问. 和谐数组是指一个数组里元素的最大值和最小值之间的差 ...

  9. md文件批量转化为html

    任务描述 博客的源文件一般以md文件保存 读取md源文件解析为html代码,然后嵌入到body中去 公式部分,需要使用第三方js库加载 实现办法 基于Django实现,进入webpage页面,然后通过 ...

  10. 使用树莓派搭建LoRaWAN网关并接入腾讯云物联网开发平台

    安装树莓派环境 制作镜像 下载img文件烧录器 传送门:img文件烧录器地址,下载完成之后双击安装 下载镜像文件 传送门:树莓派系统镜像 推荐下载这个版本的img,因为有桌面,并且大小适中. 下载完之 ...