远程执行服务器端命令程序(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。

猜你喜欢

转载自reasoning-lipl.iteye.com/blog/2041101