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 ...
随机推荐
- 你需要Mobx还是Redux?
在过去一年,越来越多的项目继续或者开始使用React和Redux开发,这是目前前端业内很普遍的一种前端项目解决方案,但是随着开发项目越来越多,越来越多样化时,个人又有了不同的感受和想法.是不是因为已经 ...
- 超越村后端开发(5:远程同步本地与服务器端的MySQL数据库)
1.同步MySQL数据库 服务器选用的华为云,安装了Ubuntu18.04,华为云默认是以root用户登录的. 1.使用Xshell6连接华为云 ls 2.Ubuntu18.04安装MySQL5.7 ...
- 20175221 MyCP(课下作业,必做)
MyCP(课下作业,必做) 任务详情 编写MyCP.java 实现类似Linux下cp XXX1 XXX2的功能,要求MyCP支持两个参数: - java MyCP -tx XXX1.txt XXX2 ...
- SpringBoot入门:Hello World
1.Open IDEA,choose "New-->Project" 2.Choose "Spring Initializr" 3. Choose jav ...
- Linux服务与进程状态
linux进程的几个状态 Linux进程状态:R (TASK_RUNNING),可执行状态&运行状态(在run_queue队列里的状态) Linux进程状态:S (TASK_INTERRUPT ...
- kubernetes之管理容器的计算资源
资源类型 CPU 和 memory 都是 资源类型.资源类型具有基本单位.CPU 的单位是 core,memory 的单位是 byte.这些都统称为计算资源. CPU含义: CPU 资源的限制和请求以 ...
- Aras 引入外部的dll
1.在vs中编译项目.然后找到项目目录生成好的dll. 2.找到Aras的安装目录:...\Aras\Innovator\Innovator\Server,将dll放到该目录下.然后在该目录下找到me ...
- Standford NLP study
Homepage https://stanfordnlp.github.io/CoreNLP/index.html Source Code: https://github.com/stanfordnl ...
- 背景上实现阴影——linear-gradient
/*从元素顶部有条阴影,两种方式,第二种更好,能控制阴影的宽度*/background-image: linear-gradient(0deg, rgba(226, 226, 226, 0) 97%, ...
- Codeforces Round #527 (Div. 3) C. Prefixes and Suffixes
题目链接 题意:给你一个长度n,还有2*n-2个字符串,长度相同的字符串一个数前缀一个是后缀,让你把每个串标一下是前缀还是后缀,输出任意解即可. 思路;因为不知道前缀还是后缀所以只能搜,但可以肯定的是 ...