溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Windows系統(tǒng)下如何使用Java代碼操作Linux

發(fā)布時(shí)間:2020-10-19 16:06:21 來源:億速云 閱讀:122 作者:小新 欄目:編程語言

Windows系統(tǒng)下如何使用Java代碼操作Linux?這個(gè)問題可能是我們?nèi)粘W(xué)習(xí)或工作經(jīng)常見到的。希望通過這個(gè)問題能讓你收獲頗深。下面是小編給大家?guī)淼膮⒖純?nèi)容,讓我們一起來看看吧!

一、場(chǎng)景描述:

  主項(xiàng)目(Web)部署在Windows下,算法項(xiàng)目(TensorFlow)部署在Linux環(huán)境下。

二、依賴環(huán)境(Jar)

        <!--Java SSH插件-->
        <dependency>
            <groupId>ch.ethz.ganymed</groupId>
            <artifactId>ganymed-ssh3</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.ssh3.ChannelCondition;
import ch.ethz.ssh3.Connection;
import ch.ethz.ssh3.Session;
import ch.ethz.ssh3.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;

    /**
     * 構(gòu)造函數(shù)
     *
     * @param ip
     * @param userName
     * @param password
     */
    public RemoteShellExecutor(String ip, String userName, String password) {
        this.ip = ip;
        this.userName = userName;
        this.password = password;
    }

    /**
     * 鏈接遠(yuǎn)程桌面
     *
     * @return
     * @throws IOException
     */
    private boolean login() throws IOException {
        conn = new ch.ethz.ssh3.Connection(ip);
        conn.connect();
        return conn.authenticateWithPassword(userName, password);
    }

    /**
     * 執(zhí)行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("遠(yuǎn)程鏈接失敗:" + ip);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.close();
            }
            IOUtils.closeQuietly(stdOut);
            IOUtils.closeQuietly(stdErr);
        }
        return ret;
    }

    /**
     * 獲取執(zhí)行過程輸出
     *
     * @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下某個(gè)文件數(shù)據(jù),將其拷貝到本地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);
            //設(shè)置用戶名和密碼
            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;//行號(hào)
                            //一次讀入一行,直到讀入null為文件結(jié)束
                            while ((tempString = reader.readLine()) != null) {
                                //顯示行號(hào)
                                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;
    }
}

感謝各位的閱讀!看完上述內(nèi)容,你們對(duì)Windows系統(tǒng)下如何使用Java代碼操作Linux大概了解了嗎?希望文章內(nèi)容對(duì)大家有所幫助。如果想了解更多相關(guān)文章內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI