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 {
//执行列表展示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服务器并执行命令及上传文件的更多相关文章
- ssh远程连接linux服务器并执行命令
详细方法: SSHClient中的方法 参数和参数说明 connect(实现ssh连接和校验) hostname:目标主机地址 port:主机端口 username:校验的用户名 password:登 ...
- Linux系统通过AWS命令行上传文件至S3
打开你的AWS控制台: 在IAM中创建一个新用户(比如test),创建时它会自动创建一个用户安全凭证,是由“访问密钥ID”和“私有访问密钥”组成的,请记住它并下载该凭证,后面会用到它: 选择你刚创建的 ...
- python批量操作Linux服务器脚本,ssh密码登录(执行命令、上传、下载)(一)
-*- paramiko.util.log_to_file( ssh = paramiko.SSHClient() ssh.set_missing ...
- python批量操作Linux服务器脚本,key登录(执行命令、上传、下载)(二)
-*- 2 #批量操作linux服务器(执行命令,上传,下载) 3 #!/usr/bin/python 4 import paramiko 5 import datetime ...
- Sublime 远程连接 Linux服务器
Sublime是一款强大的编辑器,它的强大体现在它强大的插件. 要实现Sublime 远程连接 Linux服务器,需要使用插件SFTP. 一. 插件安装 用Package Control安装插件按下C ...
- widows本地-xshell实现远程连接linux服务器图形界面
本地环境远程连接linux图形界面,常用的实现工具有,VNC.Puty.Xshell等,这里我们用的xshell manager: Xmanager简介:Xmanager是一个运行于 Windows平 ...
- Window系统远程连接Linux服务器(非桌面系统)
Window系统远程连接Linux服务器(非桌面系统) Window系统远程连接Linux服务器(非桌面系统),步骤: 第一步:下载Xshell远程登录软件:第二步:设置Linux服务器的IP.端口. ...
- widows终端远程连接Linux服务器
一.前言 为什么不是远程连接Linux服务器? 因为我不会,远程连接window我就用电脑自带的“远程桌面连接”. 以下所述都是在CentOS操作系统下的. 服务器刚换成Linux的时候很迷茫,感觉无 ...
- vscode远程连接linux服务器,可视化绘图
vscode远程连接linux服务器 想要实现的功能和解决方案 实现的功能: windows下直接使用远程linux服务器的python环境和文件来编写和运行py文件, 实时的编写py文件,和可视化绘 ...
随机推荐
- Jupyter PPT
安装 pip install jupyter pip install RISE jupyter-nbextension install rise --py --sys-prefix jupyter-n ...
- java_数据类型转换、运算符
数据类型转换 Java程序中要求参与计算的数据,必须要保证数据类型一致,如果数据类型不一致将发生类型的转换. 1.1 自动转换 一个 int 类型变量和一个 byte 类型变量进行加法运算,运算结果, ...
- redis(一)内部机制的介绍和启动过程
redis(一)内部机制的介绍和启动过程 redis的基本介绍 redis服务端 redis客户端 redis的持久化 redis中的文件事件和时间时间 redis的启动过程 redis的基本介绍 r ...
- C#LeetCode刷题之#747-至少是其他数字两倍的最大数( Largest Number At Least Twice of Others)
问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3746 访问. 在一个给定的数组nums中,总是存在一个最大元素 ...
- 生成对抗网络GAN介绍
GAN原理 生成对抗网络GAN由生成器和判别器两部分组成: 判别器是常规的神经网络分类器,一半时间判别器接收来自训练数据中的真实图像,另一半时间收到来自生成器中的虚假图像.训练判别器使得对于真实图像, ...
- Ubuntu无法安装 英伟达显卡
安装Ubuntu无法正常驱动英伟达,这时需要在启动参数中添加nomodset 如果不会添加参数可以参考这篇文章:安装ubuntu时黑屏三种解决办法
- guice的能力简述
guice这个google出的bean容器框架,ES有用到他. 能干什么 是一个bean容器 能AOP 能力细分与使用方式 以module创建injector.可以看成是一个容器.Module需要自定 ...
- Eclipse中构建maven项目的两种方式
Eclipse中构建maven项目的两种方式 方式一: 1.构建maven项目 1.1 新建meven项目,可在Other中找到maven文件夹 1.2 进入maven项目后,点击next 1.3 在 ...
- kali安装open-vm-tools实现虚拟机交互
普通的VMware tools 弱爆了 安装具有复制粘贴功能的open-vm-tools.servic: 切记:如果之前已经安装了VMware tools,一定要删除:vmware-uninstall ...
- IDEA常用快捷键Mac os和Windows对照--用到了就会更新
之前公司用了一段的MacBookPro,离职后自己入手了一台MacBookPro.但是现在的公司中使用的电脑是古老的win7,两个系统的键盘有些许差别,而且快捷键也略有不同.最近因为疫情影响,在家远程 ...