最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

1. 使用JDK自帶的RunTime類和Process類實現(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é)束");
    }
}

/**
 *   消費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 實現(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();
    // 驗證用戶密碼
    conn.authenticateWithPassword(username, password);
    Session session = conn.openSession();
    session.execCommand("cd /home/winnie; ls;");
    
    // 消費所有輸入流
    String inStr = consumeInputStream(session.getStdout());
    String errStr = consumeInputStream(session.getStderr());
    
    session.close;
    conn.close();
}

/**
 *   消費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實現(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();
   
    // 消費所有輸入流,必須在exec之后
    String inStr = consumeInputStream(exec.getInputStream());
    String errStr = consumeInputStream(exec.getErrStream());
    
    exec.disconnect();
    session.disconnect();
}

/**
 *   消費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、端口、用戶名和密碼,連接遠程服務(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");
        // 從遠程服務(wù)器/opt下的index.html下載到本地項目根路徑下
        scpClient.getFile("/opt/index.html","./");
       // 把本地項目下根路徑下的index.html上傳到遠程服務(wù)器/opt目錄下
        scpClient.putFile("./index.html","/opt");
    }
}

總結(jié) 

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

相關(guān)文章

最新評論

五莲县| 梓潼县| 太谷县| 大荔县| 江北区| 阿拉善右旗| 定襄县| 南丰县| 宜宾市| 阿图什市| 宜丰县| 尼勒克县| 长阳| 册亨县| 镇康县| 公主岭市| 盱眙县| 郓城县| 江永县| 湛江市| 武汉市| 青州市| 霍邱县| 明溪县| 屏山县| 永丰县| 通辽市| 扶风县| 邹平县| 内丘县| 碌曲县| 孝昌县| 铁力市| 台湾省| 郴州市| 通州区| 邓州市| 华池县| 广东省| 江西省| 开远市|