遠程執行服務器端命令程序(jsch實現)

        通過jsch可以實現基於sftp協議的文件傳輸,使用的是ChannelSftp類,如果要在程序中實現啓動服務器的一個腳本,執行某個系統命令的話,就需要用到另一個channel類了,就是ChannelExec類。

        如果項目採用maven構建的話,引入

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

 

        代碼示列:

package com.lipl;

import com.jcraft.jsch.*;

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

/**
 * @author lipenglong
 * @ClassName:
 * @Description: this is a class desc.
 * @date 14-4-1 上午10:44
 */
public class JschCommand {
    private Session session = null;
    private Channel channel = null;

    private String sftpHost = "localhost";
    private int sftpPort = 22;
    private String sftpUserName = "petric";
    private String sftpPassword = "123";
    private int timeout = 30000;

    /**
     * 獲取連接
     * @return
     */
    private ChannelExec getChannelExec() {
        try {
            if (channel != null && channel.isConnected()) {
                return (ChannelExec) channel;
            }
            JSch jSch = new JSch();
            if (session == null || !session.isConnected()) {
                session = jSch.getSession(sftpUserName, sftpHost, sftpPort);
                session.setPassword(sftpPassword);
                Properties config = new Properties();
                config.put("StrictHostKeyChecking", "no");
                session.setConfig(config);
                session.setTimeout(timeout);
                session.connect();
            }
            channel = session.openChannel("exec");
        } catch (Exception e) {
            if (session != null) {
                session.disconnect();
                session = null;
            }
            channel = null;
        }
        return channel == null ? null : (ChannelExec) channel;
    }

    /**
     * 關閉連接
     */
    private void closeChannel() {
        try {
            if (channel != null) {
                channel.disconnect();
                channel = null;
            }
            if (session != null) {
                session.disconnect();
                session = null;
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    /**
     * 執行服務器端命令
     */
    public boolean executeCommand(String command) {
        boolean flag = false;
        ChannelExec channelExec = getChannelExec();
        if (channelExec == null) {
            return false;
        }
        try {
            channelExec.setInputStream(null);
            channelExec.setErrStream(System.err);
            channelExec.setCommand(command);

            InputStream in = channelExec.getInputStream();
            channelExec.connect();

            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"));
            String line = null;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            reader.close();
            closeChannel();

            flag = true;
        } catch (Exception e) {
            System.out.println(e);
            flag = false;
        }
        return flag;
    }

    public static void main(String[] args) {
        JschCommand jschCommand = new JschCommand();
        System.out.println(jschCommand.executeCommand("date"));
        System.out.println("----------------------------------");
        System.out.println(jschCommand.executeCommand("ruby Demo.rb"));
        System.out.println("----------------------------------");
        System.out.println(jschCommand.executeCommand("touch abc.txt"));
        System.out.println("----------------------------------");
        System.out.println(jschCommand.executeCommand("rm abc.txt"));
    }
}

 

通過ChannelExec類可以實現執行服務器命令,如date, touch, rm等,可以執行服務器上我們寫好的某個腳本,如Demo.rb。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章