1. 程式人生 > >java本地呼叫cmd,shell命令,遠端呼叫Linux執行命令方法總結

java本地呼叫cmd,shell命令,遠端呼叫Linux執行命令方法總結

有時候經常會碰到需要遠端呼叫Linux或者本地呼叫Linux或者本地呼叫cmd的一些命令,最近小結了一下這幾種用法

本地呼叫cmd命令

    @Test
    public void testCmd()throws Exception{
        String cmd="cmd /c date"; //命令的前面必須要有cmd /c
        execCmd(cmd);
    }

    public static void execCmd(String cmd){
        try{
            Runtime rt = Runtime.getRuntime();
            //執行命令, 最後一個引數,可以使用new File("path")指定執行的命令的位置
Process proc = rt.exec(cmd,null,null); InputStream stderr = proc.getInputStream(); InputStreamReader isr = new InputStreamReader(stderr,"GBK"); BufferedReader br = new BufferedReader(isr); String line=""; while ((line = br.readLine()) != null
) { // 打印出命令執行的結果 System.out.println(line); } }catch (Exception e){ e.printStackTrace(); } }

本地呼叫Linux命令

    @Test
    public void testCmd()throws Exception{
        String cmd="/bin/sh -c date"; //命令的前面必須要有/bin/sh -c
        execCmd(cmd);

    }

    public
static void execCmd(String cmd){ try{ Runtime rt = Runtime.getRuntime(); //執行命令, 最後一個引數,可以使用new File("path")指定執行的命令的位置 Process proc = rt.exec(cmd,null,null); InputStream stderr = proc.getInputStream(); InputStreamReader isr = new InputStreamReader(stderr,"GBK"); BufferedReader br = new BufferedReader(isr); String line=""; while ((line = br.readLine()) != null) { // 打印出命令執行的結果 System.out.println(line); } }catch (Exception e){ e.printStackTrace(); } }

遠端呼叫Linux執行命令

jar包下載

http://central.maven.org/maven2/com/jcraft/jsch/0.1.54/jsch-0.1.54.jar

或者maven引用

<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.54</version>
</dependency>

參考程式碼如下

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class SSHHelper {
    /**
     * 遠端 執行命令並返回結果呼叫過程 是同步的(執行完才會返回)
     * @param host  主機名
     * @param user  使用者名稱
     * @param psw   密碼
     * @param port  埠
     * @param command   命令
     * @return
     */
    public static String exec(String host,String user,String psw,int port,String command){
        StringBuffer sb= new StringBuffer();
        Session session =null;
        ChannelExec openChannel =null;
        try {
            JSch jsch=new JSch();
            session = jsch.getSession(user, host, port);
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");//跳過公鑰的詢問
            session.setConfig(config);
            session.setPassword(psw);
            session.connect(5000);//設定連線的超時時間
            openChannel = (ChannelExec) session.openChannel("exec");
            openChannel.setCommand(command); //執行命令
            int exitStatus = openChannel.getExitStatus(); //退出狀態為-1,直到通道關閉
            System.out.println(exitStatus);

            // 下面是得到輸出的內容
            openChannel.connect();
            InputStream in = openChannel.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            String buf = null;
            while ((buf = reader.readLine()) != null) {
                sb.append(buf+"\n");
            }
        } catch (JSchException | IOException e) {
            sb.append(e.getMessage()+"\n");
        }finally{
            if(openChannel!=null&&!openChannel.isClosed()){
                openChannel.disconnect();
            }
            if(session!=null&&session.isConnected()){
                session.disconnect();
            }
        }
        return sb.toString();
    }


    public static void main(String args[]){
        String exec = exec("192.168.1.xx", "user", "name", 22, "ls");
        System.out.println(exec);
    }
}