欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java遠(yuǎn)程連接Linux執(zhí)行命令的3種方式完整代碼

 更新時(shí)間:2024年06月07日 09:32:33   作者:凡客丶  
在一些Java應(yīng)用程序中需要執(zhí)行一些Linux系統(tǒng)命令,例如服務(wù)器資源查看、文件操作等,這篇文章主要給大家介紹了關(guān)于java遠(yuǎn)程連接Linux執(zhí)行命令的3種方式,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下

1. 使用JDK自帶的RunTime類和Process類實(shí)現(xiàn)

public static void main(String[] args){
    Process proc = RunTime.getRunTime().exec("cd /home/tom; ls;")

    // 標(biāo)準(zhǔn)輸入流(必須寫在 waitFor 之前)
    String inStr = consumeInputStream(proc.getInputStream());
    // 標(biāo)準(zhǔn)錯誤流(必須寫在 waitFor 之前)
    String errStr = consumeInputStream(proc.getErrorStream());

    int retCode = proc.waitFor();
    if(retCode == 0){
        System.out.println("程序正常執(zhí)行結(jié)束");
    }
}

/**
 *   消費(fèi)inputstream,并返回
 */
public static String consumeInputStream(InputStream is){
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String s ;
    StringBuilder sb = new StringBuilder();
    while((s=br.readLine())!=null){
        System.out.println(s);
        sb.append(s);
    }
    return sb.toString();
}

2. ganymed-ssh2 實(shí)現(xiàn)

pom

<!--ganymed-ssh2包-->
<dependency>
    <groupId>ch.ethz.ganymed</groupId>
    <artifactId>ganymed-ssh2</artifactId>
    <version>build210</version>
</dependency>
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;

public static void main(String[] args){
    String host = "210.38.162.181";
    int port = 22;
    String username = "root";
    String password = "root";
    // 創(chuàng)建連接
    Connection conn = new Connection(host, port);
    // 啟動連接
    conn.connection();
    // 驗(yàn)證用戶密碼
    conn.authenticateWithPassword(username, password);
    Session session = conn.openSession();
    session.execCommand("cd /home/winnie; ls;");
    
    // 消費(fèi)所有輸入流
    String inStr = consumeInputStream(session.getStdout());
    String errStr = consumeInputStream(session.getStderr());
    
    session.close;
    conn.close();
}

/**
 *   消費(fèi)inputstream,并返回
 */
public static String consumeInputStream(InputStream is){
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String s ;
    StringBuilder sb = new StringBuilder();
    while((s=br.readLine())!=null){
        System.out.println(s);
        sb.append(s);
    }
    return sb.toString();
}

3. jsch實(shí)現(xiàn)

pom

<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.55</version>
</dependency>
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public static void main(String[] args){
    String host = "210.38.162.181";
    int port = 22;
    String username = "root";
    String password = "root";
    // 創(chuàng)建JSch
    JSch jSch = new JSch();
    // 獲取session
    Session session = jSch.getSession(username, host, port);
    session.setPassword(password);
    Properties prop = new Properties();
    prop.put("StrictHostKeyChecking", "no");
    session.setProperties(prop);
    // 啟動連接
    session.connect();
    ChannelExec exec = (ChannelExec)session.openChannel("exec");
    exec.setCommand("cd /home/winnie; ls;");
    exec.setInputStream(null);
    exec.setErrStream(System.err);
    exec.connect();
   
    // 消費(fèi)所有輸入流,必須在exec之后
    String inStr = consumeInputStream(exec.getInputStream());
    String errStr = consumeInputStream(exec.getErrStream());
    
    exec.disconnect();
    session.disconnect();
}

/**
 *   消費(fèi)inputstream,并返回
 */
public static String consumeInputStream(InputStream is){
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String s ;
    StringBuilder sb = new StringBuilder();
    while((s=br.readLine())!=null){
        System.out.println(s);
        sb.append(s);
    }
    return sb.toString();
}

4. 完整代碼:

執(zhí)行shell命令

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>
<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.55</version>
</dependency>
<dependency>
    <groupId>ch.ethz.ganymed</groupId>
    <artifactId>ganymed-ssh2</artifactId>
    <version>build210</version>
</dependency>
import cn.hutool.core.io.IoUtil;
import com.jcraft.jsch.ChannelShell;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Vector;

/**
 * shell腳本調(diào)用類
 *
 * @author Micky
 */
public class SshUtil {
    private static final Logger logger = LoggerFactory.getLogger(SshUtil.class);
    private Vector<String> stdout;
    // 會話session
    Session session;
    //輸入IP、端口、用戶名和密碼,連接遠(yuǎn)程服務(wù)器
    public SshUtil(final String ipAddress, final String username, final String password, int port) {
        try {
            JSch jsch = new JSch();
            session = jsch.getSession(username, ipAddress, port);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect(100000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public int execute(final String command) {
        int returnCode = 0;
        ChannelShell channel = null;
        PrintWriter printWriter = null;
        BufferedReader input = null;
        stdout = new Vector<String>();
        try {
            channel = (ChannelShell) session.openChannel("shell");
            channel.connect();
            input = new BufferedReader(new InputStreamReader(channel.getInputStream()));
            printWriter = new PrintWriter(channel.getOutputStream());
            printWriter.println(command);
            printWriter.println("exit");
            printWriter.flush();
            logger.info("The remote command is: ");
            String line;
            while ((line = input.readLine()) != null) {
                stdout.add(line);
                System.out.println(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }finally {
            IoUtil.close(printWriter);
            IoUtil.close(input);
            if (channel != null) {
                channel.disconnect();
            }
        }
        return returnCode;
    }

    // 斷開連接
    public void close(){
        if (session != null) {
            session.disconnect();
        }
    }
    // 執(zhí)行命令獲取執(zhí)行結(jié)果
    public String executeForResult(String command) {
        execute(command);
        StringBuilder sb = new StringBuilder();
        for (String str : stdout) {
            sb.append(str);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
    	String cmd = "ls /opt/";
        SshUtil execute = new SshUtil("XXX","abc","XXX",22);
        // 執(zhí)行命令
        String result = execute.executeForResult(cmd);
        System.out.println(result);
        execute.close();
    }
}

下載和上傳文件

/**
 * 下載和上傳文件
 */
public class ScpClientUtil {

    private String ip;
    private int port;
    private String username;
    private String password;

    static private ScpClientUtil instance;

    static synchronized public ScpClientUtil getInstance(String ip, int port, String username, String passward) {
        if (instance == null) {
            instance = new ScpClientUtil(ip, port, username, passward);
        }
        return instance;
    }

    public ScpClientUtil(String ip, int port, String username, String passward) {
        this.ip = ip;
        this.port = port;
        this.username = username;
        this.password = passward;
    }

    public void getFile(String remoteFile, String localTargetDirectory) {
        Connection conn = new Connection(ip, port);
        try {
            conn.connect();
            boolean isAuthenticated = conn.authenticateWithPassword(username, password);
            if (!isAuthenticated) {
                System.err.println("authentication failed");
            }
            SCPClient client = new SCPClient(conn);
            client.get(remoteFile, localTargetDirectory);
        } catch (IOException ex) {
            ex.printStackTrace();
        }finally{
            conn.close();
        }
    }

    public void putFile(String localFile, String remoteTargetDirectory) {
        putFile(localFile, null, remoteTargetDirectory);
    }

    public void putFile(String localFile, String remoteFileName, String remoteTargetDirectory) {
        putFile(localFile, remoteFileName, remoteTargetDirectory,null);
    }

    public void putFile(String localFile, String remoteFileName, String remoteTargetDirectory, String mode) {
        Connection conn = new Connection(ip, port);
        try {
            conn.connect();
            boolean isAuthenticated = conn.authenticateWithPassword(username, password);
            if (!isAuthenticated) {
                System.err.println("authentication failed");
            }
            SCPClient client = new SCPClient(conn);
            if ((mode == null) || (mode.length() == 0)) {
                mode = "0600";
            }
            if (remoteFileName == null) {
                client.put(localFile, remoteTargetDirectory);
            } else {
                client.put(localFile, remoteFileName, remoteTargetDirectory, mode);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }finally{
            conn.close();
        }
    }

    public static void main(String[] args) {
        ScpClientUtil scpClient = ScpClientUtil.getInstance("XXX", 22, "XXX", "XXX");
        // 從遠(yuǎn)程服務(wù)器/opt下的index.html下載到本地項(xiàng)目根路徑下
        scpClient.getFile("/opt/index.html","./");
       // 把本地項(xiàng)目下根路徑下的index.html上傳到遠(yuǎn)程服務(wù)器/opt目錄下
        scpClient.putFile("./index.html","/opt");
    }
}

總結(jié) 

到此這篇關(guān)于java遠(yuǎn)程連接Linux執(zhí)行命令的3種方式的文章就介紹到這了,更多相關(guān)java遠(yuǎn)程連接Linux執(zhí)行命令內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Spring 多線程下注入bean問題詳解

    Spring 多線程下注入bean問題詳解

    本篇文章主要介紹了Spring 多線程下注入bean問題詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-10-10
  • springboot在idea下debug調(diào)試熱部署問題

    springboot在idea下debug調(diào)試熱部署問題

    這篇文章主要介紹了springboot在idea下debug調(diào)試熱部署問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-02-02
  • Map按單個(gè)或多個(gè)Value排序當(dāng)Value相同時(shí)按Key排序

    Map按單個(gè)或多個(gè)Value排序當(dāng)Value相同時(shí)按Key排序

    Map可以先按照value進(jìn)行排序,然后按照key進(jìn)行排序。 或者先按照key進(jìn)行排序,然后按照value進(jìn)行排序,這樣操作都行,這篇文章主要介紹了Map按單個(gè)或多個(gè)Value排序,當(dāng)Value相同時(shí)按Key排序,需要的朋友可以參考下
    2023-02-02
  • java中匿名內(nèi)部類解讀分析

    java中匿名內(nèi)部類解讀分析

    本篇文章介紹了,java中匿名內(nèi)部類解讀分析。需要的朋友參考下
    2013-05-05
  • 初識Java環(huán)境變量配置及IDEA

    初識Java環(huán)境變量配置及IDEA

    這篇文章主要介紹了Java環(huán)境變量配置及IDEA,本文通過圖文實(shí)例相結(jié)合給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-03-03
  • Java 靜態(tài)數(shù)據(jù)初始化的示例代碼

    Java 靜態(tài)數(shù)據(jù)初始化的示例代碼

    這篇文章主要介紹了Java 靜態(tài)數(shù)據(jù)初始化的示例代碼,幫助大家更好的理解和學(xué)習(xí)Java,感興趣的朋友可以了解下
    2020-09-09
  • Mybatis中通用Mapper的InsertList()用法

    Mybatis中通用Mapper的InsertList()用法

    文章介紹了通用Mapper中的insertList()方法在批量新增時(shí)的使用方式,包括自增ID和自定義ID的情況,對于自增ID,使用tk.mybatis.mapper.additional.insert.InsertListMapper包下的insertList()方法;對于自定義ID,需要重寫insertList()方法
    2025-02-02
  • 一文盤點(diǎn)五種最常用的Java加密算法

    一文盤點(diǎn)五種最常用的Java加密算法

    大家平時(shí)的工作中,可能也在很多地方用到了加密、解密,比如:支付功能等,所以本文為大家盤點(diǎn)了Java中五個(gè)常用的加密算法,希望對大家有所幫助
    2023-06-06
  • java自帶的四種線程池實(shí)例詳解

    java自帶的四種線程池實(shí)例詳解

    java線程的創(chuàng)建非常昂貴,需要JVM和OS(操作系統(tǒng))互相配合完成大量的工作,下面這篇文章主要給大家介紹了關(guān)于java自帶的四種線程池的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下
    2022-04-04
  • 一個(gè)簡單的Spring容器初始化流程詳解

    一個(gè)簡單的Spring容器初始化流程詳解

    這篇文章主要給大家介紹了一個(gè)簡單的Spring容器初始化流程的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-01-01

最新評論