Windows环境下应用Java代码操作Linux资源
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>欢迎转载,转载请注明出处-VirgoArt,www.cnblogs.com
一、场景描述:
主项目(Web)部署在Windows下,算法项目(TensorFlow)部署在Linux环境下。
二、依赖环境(Jar)
<!--Java SSH插件-->
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>build210</version>
</dependency>
<dependency>
<groupId>sshtools</groupId>
<artifactId>j2ssh-core</artifactId>
<version>0.2.9</version>
</dependency> <dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
三、后端代码
package cn.virgo.audio.utils; import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import com.sshtools.j2ssh.SshClient;
import com.sshtools.j2ssh.authentication.AuthenticationProtocolState;
import com.sshtools.j2ssh.authentication.PasswordAuthenticationClient;
import com.sshtools.j2ssh.sftp.SftpFile;
import org.apache.commons.io.IOUtils; import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List; public class RemoteShellExecutor { private Connection conn; private String ip; private String userName; private String password; private String charset = Charset.defaultCharset().toString(); private static final int TIME_OUT = 1000 * 5 * 60; /**
* 构造函数
*
* @param ip
* @param userName
* @param password
*/
public RemoteShellExecutor(String ip, String userName, String password) {
this.ip = ip;
this.userName = userName;
this.password = password;
} /**
* 链接远程桌面
*
* @return
* @throws IOException
*/
private boolean login() throws IOException {
conn = new ch.ethz.ssh2.Connection(ip);
conn.connect();
return conn.authenticateWithPassword(userName, password);
} /**
* 执行shell
*
* @param cmds
* @return
* @throws Exception
*/
public int exec(String cmds) throws Exception {
InputStream stdOut = null;
InputStream stdErr = null;
int ret = -1;
try {
if (login()) {
Session session = conn.openSession();
session.execCommand(cmds);
stdOut = new StreamGobbler(session.getStdout());
processStream(stdOut, charset);
stdErr = new StreamGobbler(session.getStderr());
processStream(stdErr, charset);
session.waitForCondition(ChannelCondition.EXIT_STATUS, TIME_OUT);
ret = session.getExitStatus();
} else {
throw new Exception("远程链接失败:" + ip);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.close();
}
IOUtils.closeQuietly(stdOut);
IOUtils.closeQuietly(stdErr);
}
return ret;
} /**
* 获取执行过程输出
*
* @param in
* @param charset
* @return
* @throws IOException
*/
private void processStream(InputStream in, String charset) throws IOException {
byte[] buf = new byte[1024];
while (in.read(buf) != -1) {
System.out.println(new String(buf, charset));
}
} /**
* 获取Linux下某个文件数据,将其拷贝到本地tmpPath下
*/
public List<String> getCaleResByFileFromSSH(String filePath, String filename, String tmpPath) {
List<String> resList = new ArrayList<>();
SshClient client = new SshClient();
try {
client.connect(this.ip);
//设置用户名和密码
PasswordAuthenticationClient pwd = new PasswordAuthenticationClient();
pwd.setUsername(this.userName);
pwd.setPassword(this.password);
int result = client.authenticate(pwd);
if (result == AuthenticationProtocolState.COMPLETE) {//如果连接完成
List<SftpFile> list = client.openSftpClient().ls(filePath);
for (SftpFile f : list) {
if (f.getFilename().equals(filename)) {
OutputStream os = new FileOutputStream(tmpPath + f.getFilename());
client.openSftpClient().get(f.getAbsolutePath(), os);
//以行为单位读取文件start
File file = new File(tmpPath + f.getFilename());
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;//行号
//一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
//显示行号
System.out.println("line " + line + ": " + tempString);
resList.add(tempString);
line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
//以行为单位读取文件end
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return resList;
}
public List<String> getCaleResByFileFromSFTP(String remoteFile,String localFile){
List<String> resList = new ArrayList<>();
try {
if(Paths.get(localFile).toFile().exists()){
Paths.get(localFile).toFile().delete();
}
Paths.get(localFile).toFile().createNewFile();
FileOutputStream fout = new FileOutputStream(new File(localFile));
login();
SCPClient scp =conn.createSCPClient();
scp.get(remoteFile,fout);
fout.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(localFile)), "UTF-8"));
String tempString = null;
int line = 1;//行号
//一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
//显示行号
System.out.println("line " + line + ": " + tempString);
resList.add(tempString);
line++;
}
reader.close();
}catch (Exception e){
e.printStackTrace();
}
return resList;
}
}
Windows环境下应用Java代码操作Linux资源的更多相关文章
- windows环境下安装pymysql(操作带图)
在windows环境下安装pymysql,首先要找到python的安装位置,如果在c盘,启动cmd的时候,要获取管理员权限. 具体步骤,一,管理员模式启动cmd.在箭头指定位置,搜索cmd,出现快捷方 ...
- 在linux环境下让java代码生效的步骤
1.kill jboss 2.compile 3.deploy 4.bootstrap jboss.
- windows环境下搭建Java开发环境(一):jdk安装和配置
一.资源下载 官网:http://www.oracle.com/technetwork/java/javase/downloads/index.html 本人安装的是jdk1.8,百度云资源:链接:h ...
- windows环境下搭建Java开发环境(二):Tomcat安装和配置
一.资源下载 官网:http://tomcat.apache.org/ 本人安装的是Tomcat8.5,安装包百度云资源:链接:https://pan.baidu.com/s/17SDFsoS0yAP ...
- windows环境下搭建Java开发环境(三)——Maven环境配置使用 (转)
1. 安装配置Maven: 1.1 从Apache网站 http://maven.apache.org/ 下载并且解压缩安装Apache Maven. Maven下载地址: http://maven. ...
- 【备忘】windows环境下20行php代码搞定音频裁剪
先上图,由于最近的需求需要对语音文件进行处理,所以抽空研究了下php处理音/视频文件的处理,简单的demo处理,截取一个音频文件的前20秒,并保存新的媒体文件. 操作步骤: ①在此站点下载所需的辅助程 ...
- 【大数据系列】windows环境下搭建hadoop开发环境使用api进行基本操作
前言 搭建完hadoop集群之后在windows环境下搭建java项目进行测试 操作hdfs中的文件 版本一 package com.slp.hadoop274.hdfs; import java.i ...
- windows环境下protobuf的java操作{编译,序列化,反序列化}
google protocol buffer的使用和原理 概况: Protocol Buffers(也就是protobuf)是谷歌的语言中立的.平台中立的.可扩展的用于序列化结构化的数据: windo ...
- Windows环境下写Linux sh脚本的一次挖坑和填坑
最近在研究Docker集群和安装的时候,需要准备若干台机器.所以我为节约时间,打算批量复制VM机器,然后用sh脚本命令执行机器名称和IP等基础配置信息的修改. 具体操作:我在windows环境下,用N ...
随机推荐
- va_start
#include <stdarg.h> void va_start(va_list ap, last); type va_arg(va_list ap, type); void va_en ...
- 适用于单片机的数据加密算法:xxtea
转:https://www.cnblogs.com/LittleTiger/p/4384741.html 各位大侠在做数据传输时,有没有考虑过把数据加密起来进行传输,若在串口或者无线中把所要传的数据加 ...
- trackerClient.getConnection()为null
如题,整了个fastDFS文件服务器.但是集成项目spring boot时上传文件失败! Debug到trackerClient.getConnection()时为null.于是看了服务器上track ...
- sed命令(二)
转自:https://www.cnblogs.com/maxincai/p/5146338.html sed命令用法 sed是一种流编辑器,它是文本处理中非常有用的工具,能够完美的配合正则表达式使用, ...
- SpringMVC+Apache Shiro+JPA(hibernate)案例教学(二)基于SpringMVC+Shiro的用户登录权限验证
序: 在上一篇中,咱们已经对于项目已经做了基本的配置,这一篇文章开始学习Shiro如何对登录进行验证. 教学: 一.Shiro配置的简要说明. 有心人可能注意到了,在上一章的applicationCo ...
- 【6】学习C++之类的实例化及访问
类就像一张图纸,如果不去实例化,制造出相应的零件,用处就不会那么大. 实例化类有两种,一个是从栈中实例化对象: class TV { public: ]; int type; void changeV ...
- 在web项目启动时,执行某个方法
在web项目中有很多时候需要在项目启动时就执行一些方法,而且只需要执行一次,比如:加载解析自定义的配置文件.初始化数据库信息等等,在项目启动时就直接执行一些方法,可以减少很多繁琐的操作. 在工作中遇到 ...
- 安装pandas报错(AttributeError: 'module' object has no attribute 'main')
在pycharm中安装pandas出现报错:AttributeError: 'module' object has no attribute 'main', 刚开始以为是pip的版本太旧了,于是乎将其 ...
- UOJ #460 新年的拯救计划
清真的构造题 UOJ# 460 题意 求将$ n$个点的完全图划分成最多的生成树的数量,并输出一种构造方案 题解 首先一棵生成树有$ n-1$条边,而原完全图只有$\frac{n·(n-1)}{2}$ ...
- 开启Apache的server status监测
从httpd.conf 打开 status_module#LoadModule status_module modules/mod_status.so修改成LoadModule status_modu ...