旗下导航:搜·么
当前位置:网站首页 > JAVA教程 > 正文

Windows体系下运用Java代码操纵Linux的要领引见【JAVA教程】,Java

作者:搜教程发布时间:2019-11-27分类:JAVA教程浏览:60评论:0


导读:本篇文章给人人带来的内容是关于Windows体系下运用Java代码操纵Linux的要领引见,有肯定的参考价值,有须要的朋侪能够参考一下,愿望对你有所协助。一、场景形貌:...
本篇文章给人人带来的内容是关于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的要领引见的细致内容,更多请关注ki4网别的相干文章!

标签:Java


欢迎 发表评论: