Java SSH远程执行Shell脚本实现

此程序需要ganymed-ssh2-build210.jar包。
下载地址:http://www.ganymed.ethz.ch/ssh2/
为了调试方便,可以将\ganymed-ssh2-build210\src下的代码直接拷贝到我们的工程里,
此源码的好处就是没有依赖很多其他的包,拷贝过来干干净净。

 

package test;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

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

public class RemoteShellTool
{
    private Connection conn;
    private String ipAddr;
    private String charset = Charset.defaultCharset().toString();
    private String userName;
    private String password;

    public RemoteShellTool()
    {
    }

    public RemoteShellTool(String ipAddr, String userName, String password, String charset)
    {
        this.ipAddr = ipAddr;
        this.userName = userName;
        this.password = password;
        if (charset != null)
        {
            this.charset = charset;
            System.out.println("111111111");
        }
    }

    public boolean login() throws IOException
    {
        System.out.println("2222");
        this.conn = new Connection(this.ipAddr);
        this.conn.connect();
        return this.conn.authenticateWithPassword(this.userName, this.password);
    }

    public String exec(String cmds)
    {
        System.out.println("333");
        InputStream in = null;
        String result = "";
        try
        {
            if (login())
            {
                Session session = this.conn.openSession();
                session.execCommand(cmds);
                in = session.getStdout();
                result = processStdout(in, this.charset);
                this.conn.close();
            }
        }
        catch (IOException e1)
        {
            e1.printStackTrace();
        }
        return result;
    }

    public String processStdout(InputStream in, String charset)
    {
        System.out.println("4444");
        byte[] buf = new byte[1024];
        StringBuffer sb = new StringBuffer();
        try
        {
            while (in.read(buf) != -1)
                sb.append(new String(buf, charset));
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return sb.toString();
    }

    public static void main(String[] args)
    {
        List<String> urlList = new ArrayList<String>();

        urlList.add("192.168.4.119");// 有几个添加几个
        for (final String url : urlList)
        {
            new Thread(new Runnable()
            {
                @Override
                public void run()
                {
                    RemoteShellTool tool = new RemoteShellTool(url, "root", "123456", "utf-8");
                    tool.exec("cd /home && mkdir test");//在home目录下,创建一个test文件夹
                }
            }).start();
        }
    }
}

posted @ 2014-04-22 13:23  dafengshou888  阅读(465)  评论(0编辑  收藏  举报