登录  /  注册
首页 > Java > java教程 > 正文

Windows系统下使用Java代码操作Linux的方法介绍

不言
发布: 2019-03-21 09:34:04
转载
3104人浏览过

本篇文章给大家带来的内容是关于Windows系统下使用Java代码操作Linux的方法介绍,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

一、场景描述:

  主项目(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;
    }
}
登录后复制

以上就是Windows系统下使用Java代码操作Linux的方法介绍的详细内容,更多请关注php中文网其它相关文章!

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
来源:博客园网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号