java控制台输入cmd命令, ssh远程linux shell命令, 并打印命令输出到控制台

通过程序控制台, 输入 

Scanner scn = new Scanner(System.in);

1. 模拟, 本地cmd输入, 并显示cmd信息输出.

java控制台输入cmd命令, ssh远程linux shell命令, 并打印命令输出到控制台_第1张图片

2. 远程ssh linux服务器( 登陆本机上的虚拟机) 依赖jsch-0.1.53


    
        com.jcraft
        jsch
        0.1.53
    


执行linux服务命令(以下为idea控制台输出, 颜色字体为输入)

java控制台输入cmd命令, ssh远程linux shell命令, 并打印命令输出到控制台_第2张图片


3. 主要代码及说明

本地cmd, 与远程ssh channel类型. 建立连接后,由process/channel 的 outputStream 来建立命令输入的管道.

inputStream, errStream来接受命令输入后, 程序的输出


cmd: 主要程序如下: 

package exec.Menu.item;

import exec.Menu.MenuItem;
import exec.Menu.MenuManager;
import exec.cmd.ProcessInputMonitor;

import java.io.*;

/**
 * Created by ____DancingWolf on 2017/11/23.
 */
public class CMDMenuItem extends MenuItem {

    //cmd process
    private Process cmdProcess;

    public CMDMenuItem(String text, String code) {
        super(text, code);
    }

    @Override
    public void handler() {
        System.out.println("Execute the command for local commander");

        //input for process
        BufferedWriter output;

        //init cmd process
        try {
            //call cmd process
            this.cmdProcess = Runtime.getRuntime().exec(new String[]{"cmd.exe", "/k"}); //  /c:close after command /k: keep

            //monitor the input and output
            ProcessInputMonitor.monitorProcess(this.cmdProcess);

            output = new BufferedWriter(new OutputStreamWriter(this.cmdProcess.getOutputStream()));
        } catch (IOException e) {
            System.out.println("Init cmd process failed: " + e.getMessage());
            return;
        }

        //handler the input command
        String command;
        while(true){
            //get input new command
            command = MenuManager.getInstance().newInput("");

            if("____".equals(command)){
                break;
            }

            //exec cmd command
            try {
                output.write(command);
                output.newLine();
                output.flush();
            } catch (Exception e) {
                System.out.println("CMD Error: " + e.getMessage());
            }
        }

        //close cmd process
        try {
            output.close();
            this.cmdProcess.destroy();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //show main menu
        //MenuManager.getInstance().showMainMenu();
    }
}

ssh linux主要程序如下: 

package exec.Menu.item;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import exec.Menu.MenuItem;
import exec.Menu.MenuManager;
import exec.cmd.ProcessInputMonitor;

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.util.Properties;

/**
 * Created by ____DancingWolf on 2017/11/23.
 */
public class SSHMenuItem extends MenuItem {

    //connect session
    private JSch jsch;
    private Session sshSession;

    //exec channel
    private Channel channel;

    public SSHMenuItem(String text, String code) {
        super(text, code);
    }

    @Override
    public void handler() {
        //wait for login info
        String host = MenuManager.getInstance().newInput("Host: ");
        String port = MenuManager.getInstance().newInput("Port: ");
        String user = MenuManager.getInstance().newInput("User: ");
        String password = MenuManager.getInstance().newInput("Pswd: ");

        //create session
        jsch = new JSch();
        try {
            sshSession = jsch.getSession(user, host, Integer.valueOf(port));
            sshSession.setPassword(password);

            //try to connect
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();

            System.out.println("session created!");
        } catch (Exception e) {
            System.out.println("Failed to create ssh session: " + e.getMessage());
            return;
        }

        //do exec command
        this.receiveCommand();
    }

    /*
     * @description: do ssh command
     *
     * @author: ____DancingWolf 
     * @date: 2017/11/23
     * @param:
     * @return:
     */
    private void receiveCommand() {
        //channel output
        BufferedWriter output;

        //create channel
        try {
            channel = sshSession.openChannel("shell");
            channel.connect();
            System.out.println("channel connected!");

            //start monitor
            ProcessInputMonitor.monitorChannel(channel);

            //command writer
            output = new BufferedWriter(new OutputStreamWriter(this.channel.getOutputStream()));

            //handler the input command
            String command;
            while(true){
                //get input new command
                command = MenuManager.getInstance().newInput("");

                if("____".equals(command)){
                    break;
                }

                //exec cmd command
                try {
                    output.write(command);
                    output.newLine();
                    output.flush();
                } catch (Exception e) {
                    System.out.println("SSH Error: " + e.getMessage());
                }
            }
        } catch (Exception e) {
            System.out.println("Failed to create ssh channel: " + e.getMessage());
            return;
        } finally {
            this.close();
        }
    }

    /*
     * @description: close channel and session
     *
     * @author: ____DancingWolf 
     * @date: 2017/11/23
     * @param:
     * @return:
     */
    private void close() {
        try{
            if(null != this.channel){
                this.channel.getOutputStream().close();
                this.channel.disconnect();
            }
            if(null != this.sshSession){
                this.sshSession.disconnect();
            }
        } catch (Exception e){
            System.out.println("Error while closing: " + e.getMessage());
        }
    }
}

程序的输出监听:

package exec.cmd;

import com.jcraft.jsch.Channel;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Created by ____DancingWolf on 2017/11/23.
 */
public class ProcessInputMonitor implements Runnable {

    //输入流
    private InputStream inputStream = null;

    private ProcessInputMonitor(InputStream inputStream){
        this.inputStream = inputStream;
    }

    //start monitor process
    public static void monitorProcess(Process process){
        if(null == process){
            return;
        }

        //get normal and error input stream
        Runnable inputMonitor = new ProcessInputMonitor(process.getInputStream());
        new Thread(inputMonitor).start();

        Runnable errorInputMonitor = new ProcessInputMonitor(process.getErrorStream());
        new Thread(errorInputMonitor).start();
    }

    //start monitor channel
    public static void monitorChannel(Channel channel){
        if(null == channel){
            return;
        }

        //get normal and error input stream
        try {
            Runnable inputMonitor = new ProcessInputMonitor(channel.getInputStream());
            new Thread(inputMonitor).start();

            Runnable errorInputMonitor = new ProcessInputMonitor(channel.getExtInputStream());
            new Thread(errorInputMonitor).start();
        } catch (Exception e) {
            System.out.println("Error for monitoring channel input stream: " + e.getMessage());
        }
    }
    /*
     * @description: monitor the stream data
     *
     * @author: ____DancingWolf 
     * @date: 2017/11/23
     * @param:
     * @return:
     */
    public void run() {
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(this.inputStream, "GBK"));

            //read line data
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
            //System.out.println("Input stream closed.");
        } catch (Exception e) {
            System.out.println("Error while monitoring stream: " + e.getMessage());
        } finally {
            try {
                //close the process input stream
                this.inputStream.close();

                //close buffered stream
                if(null != br){
                    br.close();
                }
            } catch (IOException e) {
                System.out.println("Error while closing input stream: " + e.getMessage());
            }
        }
    }
}


___________________程序下载

你可能感兴趣的:(JAVA,Linux)