java操作linux shell命令并获得返回值

########自己执行成功的代码###########

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

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


public class java2Shell {
    public static void main(String[] args) throws IOException {
        Properties properties = new Properties();
        ##############shell.properties文件内容在代码下方#################
        properties.load(java2Shell.class.getClassLoader().getResourceAsStream("shell.properties")); 
        String host = properties.getProperty("HOST");
        String user = properties.getProperty("USER");
        String pwd = properties.getProperty("PWD");
        String ports = properties.getProperty("PORT");
        int port = Integer.parseInt(ports);
        String command = properties.getProperty("COMMAND");

        String exec = exec(host,user,pwd,port,command);
        System.out.println("获得执行结果:" + exec);
    }

    public static String exec(String host,String user,String pwd,int port,String command){
        StringBuffer sb = new StringBuffer();
        Session session = null;
        ChannelExec openChannel = null;
        JSch jSch = new JSch();

        try {
            session = jSch.getSession(user,pwd,port);
            Properties config = new Properties();
            config.put("StrictHostKeyChecking","no"); //跳过公钥的询问
            session.setConfig(config);
            session.setPassword(pwd);
            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");
                System.out.println(buf);
            }
        } catch (JSchException | IOException e) {
            sb.append(e.getMessage() + "\n");
        }finally {
            if(openChannel != null && !openChannel.isConnected()){
                openChannel.disconnect();
            }
            if(session != null && session.isConnected()){
                session.disconnect();
            }
        }
        return sb.toString();
    }
}

##########shell.properties文件内容###########

HOST=XXX
USER=XXX
PWD=XXX
PORT=XXX

COMMAND=cat /xx/xx.txt

你可能感兴趣的:(Java,linux)