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 ...
随机推荐
- Oracle下查看索引的语句
1. 查询一张表里面索引 select * from user_indexes where table_name=upper('bills'); 2. 查询被索引字段 select * from ...
- 使用vcastr22.swf做flash版网页视频播放器
flash的安装设置参考 Flash设置(各种版本浏览器包括低版本IE) 百度搜索下载vcastr22.swf文件 然后使用方式很简单,浏览器安装flash相关插件就能看了 视频路径主要在这里,视频 ...
- Python菜鸟快乐游戏编程_pygame(6)
Python菜鸟快乐游戏编程_pygame(博主录制,2K分辨率,超高清) https://study.163.com/course/courseMain.htm?courseId=100618802 ...
- Springboot集成Thymeleaf
Thymeleaf 官方解释: Thymeleaf是一个用于web和独立环境的现代服务器端Java模板引擎. Thymeleaf的主要目的是将优雅的自然模板引入到您的开发工作流中——以使HTML可以在 ...
- 保护代理模式-Access Proxy(Java实现)
保护代理模式-Access Proxy 保护代理模式(Access Proxy), 也叫Protect Proxy. 这种代理用于对真实对象的功能做一些访问限制, 在代理层做身份验证. 通过了验证, ...
- Springboot自定义异常处理
1.自定义异常类 import lombok.Data; @Data public class UserException extends RuntimeException { private Lon ...
- 通配符的匹配很全面, 但无法找到元素 'mvc:annotation-driven' 的声明
通配符的匹配很全面, 但无法找到元素 'mvc:annotation-driven' 的声明 错误原因是springmvc中的约束信息不对 <beans xmlns="http://w ...
- Android相关面试题---初识
一 .Activity的生命周期 Android是使用任务(Task)来管理活动的,一个任务就是一组存放在栈里的活动的集合,这个栈也被称为返回栈(Back Stack).每当我们启动一个新的活动,它会 ...
- 「IOI2018」狼人
快咕一个月了 咕咕咕 咕咕咕咕 LOJ #2865 Luogu P4899(离线) UOJ #407(强制在线) 题意 给定一棵树和若干组询问$(S,E,L,R)$ 表示你初始在$S$,想到达$E$, ...
- Python:正则表达式(二):如何使用re.search()返回的匹配对象中的具体内容呢??
在上一篇中讲述了re.seach()会返回一个对象格式的数据,如下:<_sre.SRE_Match object; span=(16, 24), match='${phone}'> 那么问 ...