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 ...
随机推荐
- posgreSQL安装失败解决方案
选择适合自己电脑版本的postgreSQL进行安装,显示安装失败,错误信息:problem running post-install step.installation may not complet ...
- C语言博客05--指针
C语言博客05--指针 1.本章学习总结 1.1 思维导图 1.2 本章学习体会及代码量学习体会 1.2.1 学习体会 在本周的学习过程中,我们学习了指针的用法.说实话,指针的用法有点绕,之前一直没搞 ...
- uboot中的中断macro宏
目录 uboot中的中断macro宏 引入 内存分配 流程概览 普通中断 保存现场 中断函数打印具体寄存器 恢复现场 软中断 空间获取 保存现场 附录速记 疑惑待解 title: uboot中的中断m ...
- Java反射-修改字段值, 反射修改static final修饰的字段
反射修改字段 咱们从最简单的例子到难, 一步一步深入. 使用反射修改一个private修饰符的变量name 咱们回到主题, 先用反射来实现一个最基础的功能吧. 其中待获取的name如下: public ...
- jQuery实现搜索框插件+豆瓣音乐接口实现豆瓣搜索框
jQuery实现搜索框插件 豆瓣音乐接口实现豆瓣搜索框 豆瓣接口有时不稳定,网络请求会报400,不要惊慌.我主要是练习一下jQuery的JSONP和封装插件. <div class=" ...
- python之路(12)网络编程
前言 基于网络通信(AF_INET)的socket(套接字)实现了TCP/UDP协议 目录 基于TCP协议的socket 基于UDP协议的socket TCP协议下粘包现象及处理 使用socketse ...
- 2018-2019-2 实验二 Java面向对象程序设计
实验内容 1.初步掌握单元测试和TDD 2.理解并掌握面向对象三要素:封装.继承.多态 3.初步掌握UML建模 4.熟悉S.O.L.I.D原则 5.了解设计模式 实验要求 1.没有Linux基础的同学 ...
- manacher最长回文子串
https://www.luogu.org/blog/codesonic/manacheralgorithm 先放上洛谷的链接,毕竟讲的真好 两道例题 luogu4555 SP7586 inline ...
- R-----shiny包的部分解释和控件介绍
R-----shiny包的部分解释和控件介绍 作者:周彦通.贾慧 shinyApp( ui = fixedPage( fixedPanel( top = 50, right=50, width=200 ...
- 中标麒麟龙芯平台--docker基础镜像制作
Docker 是一个开源的应用容器引擎,基于 Go 语言 并遵从Apache2.0协议开源.Docker 的出现为开发人员和运维人员带来了极大的便利.Docker在X86下常见的发行版Linux如Ub ...