开发一个简单的远程服务启动程序

日期:2011-06-25    阅读:125   分类:Java资料


我想基于linux上做系统部署,大家对命令行都十分熟悉,正常部署一个系统的大概流程如下:

1. 制作安装包上传
2. 解压安装包
3. 停止正在运行的服务
4. 更新程序
5. 启动服务

这几个流程除了1之外,其它都是可以用工具完成的,下面为大家介绍一种方式:

http://www.ganymed.ethz.ch/ssh2/ 提供了一个基于java的包,可以远程登录linux机器并执行命令。 那我们就可以通过这个将我们日常部署的命令写成脚本通过程序来调用,然后再做个网页界面,放一些button,部署就变的很轻松了,点点button就可以了。 下面是我封装的一个登录远程linux并执行命令的方法:

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


import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

/**
 * 远程执行shell脚本类
 * @author
 */
public class RmtShellExecutor {
   
    /**
     * 连接
     * */
    private Connection conn;

    /**
     * 远程机器IP
     * */
    private String ip;
   
    /**
     * 用户名
     * */
    private String usr;
   
    /**
     * 密码
     * */
    private String psword;

    /**
     * 超时时间
     * */
    private static final int TIME_OUT = 1000 * 5 * 60;


    /**
     * 构造函数
     * @param ip
     * @param usr
     * @param ps
     */
    public RmtShellExecutor(ServerInfo info) {
        this.ip = info.host;
        this.usr = info.usr;
        this.psword = info.password;
    }

    /**
     * 登录
     * @return
     * @throws IOException
     */
    private boolean login() throws IOException {
        conn = new Connection(ip);
        conn.connect();
        return conn.authenticateWithPassword(usr, psword);
    }

    /**
     * 执行脚本
     * @param cmds
     * @return
     * @throws Exception
     */
    public int exec(String cmds, String[] out) throws Exception {
        int ret = -1;
        try {
            if (login()) {

                Session session = conn.openSession();
               
                session.requestPTY("bash");
                session.startShell();
 
                InputStream stdout = new StreamGobbler(session.getStdout());
                InputStream stderr = new StreamGobbler(session.getStderr());
               
                BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(stdout));
                BufferedReader stderrReader = new BufferedReader(new InputStreamReader(stderr));

                PrintWriter outer = new PrintWriter(session.getStdin());
                String[] arr = cmds.split(";");
                for(int i=0;i<arr.length;i++)
                {
                    outer.println(arr[i]);
                }
                outer.println("exit");
                outer.close();
               
                session.waitForCondition(ChannelCondition.CLOSED | ChannelCondition.EOF | ChannelCondition.EXIT_STATUS, TIME_OUT);
                ret = session.getExitStatus();
               
                out[0] = processStream(stdoutReader);
                String err = processStream(stderrReader);
                if(ret != 0)
                {
                    out[0] = err;
                }
 
                session.close();
               
            } else {
                throw new Exception("Login the remote server failed: " + ip);
            }
        }
        finally
        {
            if(conn != null)
            {
                conn.close();
            }
        }
        return ret;
    }

    /**
     * @param 处理流
     * @param charset
     * @throws IOException
     * @throws UnsupportedEncodingException
     */
    private String processStream(BufferedReader in) throws Exception {
   
        StringBuilder sb = new StringBuilder();
        while(true)
        {
            String line = in.readLine();
            if(line == null)
            {
                break;
            }
            sb.append(line);
            sb.append('\n');
        }
       
        return sb.toString();
    }

    public static void main(String args[]) throws Exception {
       
        ServerInfo info = new ServerInfo();
        info.host = "the linux server host";
        info.usr = "user name";
        info.password = "password";
       
        RmtShellExecutor exe = new RmtShellExecutor(info);
        String[] out = new String[1];
        int ret = exe.exec("env", out);
        System.out.println(ret);
        System.out.println(out[0]);
    }
}

本页链接: http://www.scriptlover.com/static/705-远程-linux-服务

标签:

相关文章

网友评论

Leave a comment

 required

 required (Not published)

 required