博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Windows环境下应用Java代码操作Linux资源
阅读量:5843 次
发布时间:2019-06-18

本文共 6806 字,大约阅读时间需要 22 分钟。

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>欢迎转载,转载请注明出处-VirgoArt,www.cnblogs.com

一、场景描述:

  主项目(Web)部署在Windows下,算法项目(TensorFlow)部署在Linux环境下。

二、依赖环境(Jar)

ch.ethz.ganymed
ganymed-ssh2
build210
sshtools
j2ssh-core
0.2.9
commons-io
commons-io
2.4

三、后端代码

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
getCaleResByFileFromSSH(String filePath, String filename, String tmpPath) { List
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
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
getCaleResByFileFromSFTP(String remoteFile,String localFile){
List
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; }
}

 

转载于:https://www.cnblogs.com/virgoart/p/10569458.html

你可能感兴趣的文章
使用VMware安装CentOS7详请
查看>>
Ember.js 3.9.0-beta.3 发布,JavaScript Web 应用开发框架
查看>>
python标准库00 学习准备
查看>>
4.2. PHP crypt()
查看>>
Winform开发框架之附件管理应用
查看>>
软链接文件和硬链接文件
查看>>
Spring Cloud Config服务器
查看>>
commonservice-config配置服务搭建
查看>>
连接池的意义及阿里Druid
查看>>
ComponentOne 2019V1火热来袭!全面支持 Visual Studio 2019——亮点之WinForm篇
查看>>
全面的Spring Boot配置文件详解
查看>>
如何优雅地玩转分库分表
查看>>
Python递归函数与匿名函数
查看>>
我的友情链接
查看>>
CentOS添加永久静态路由
查看>>
mysql多实例的安装以及主从复制配置
查看>>
loadrunner安装运行一步一步来(多图)
查看>>
git请求报错 401
查看>>
动态追踪技术(四):基于 Linux bcc/BPF 实现 Go 程序动态追踪
查看>>
Cyber-Security: Linux 容器安全的十重境界
查看>>