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

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

創(chuàng)新互聯(lián)公司是一家集網(wǎng)站建設(shè),薌城企業(yè)網(wǎng)站建設(shè),薌城品牌網(wǎng)站建設(shè),網(wǎng)站定制,薌城網(wǎng)站建設(shè)報(bào)價(jià),網(wǎng)絡(luò)營(yíng)銷,網(wǎng)絡(luò)優(yōu)化,薌城網(wǎng)站推廣為一體的創(chuàng)新建站企業(yè),幫助傳統(tǒng)企業(yè)提升企業(yè)形象加強(qiáng)企業(yè)競(jìng)爭(zhēng)力。可充分滿足這一群體相比中小企業(yè)更為豐富、高端、多元的互聯(lián)網(wǎng)需求。同時(shí)我們時(shí)刻保持專業(yè)、時(shí)尚、前沿,時(shí)刻以成就客戶成長(zhǎng)自我,堅(jiān)持不斷學(xué)習(xí)、思考、沉淀、凈化自己,讓我們?yōu)楦嗟钠髽I(yè)打造出實(shí)用型網(wǎng)站。

一、場(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í)行過(guò)程輸出
     *
     * @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)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。

本文題目:Windows系統(tǒng)下如何使用Java代碼操作Linux
本文鏈接:http://muchs.cn/article4/gecpoe.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供標(biāo)簽優(yōu)化、網(wǎng)頁(yè)設(shè)計(jì)公司、網(wǎng)站導(dǎo)航App開(kāi)發(fā)、企業(yè)網(wǎng)站制作、網(wǎng)站制作

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

成都網(wǎng)站建設(shè)公司