java模拟ssh执行shell命令

来源:互联网 发布:sodu小说源码 编辑:程序博客网 时间:2024/06/14 15:55
java模拟ssh执行shell命令

       我们通常是在shell上操作linux命令,有没有可以通过java代码连接到ssh服务器来进行shell命令的操作呢?事实告诉我们是可以的,下面我们看一下源代码。
       一、maven pom.xml
                <dependency><groupId>ch.ethz.ganymed</groupId><artifactId>ganymed-ssh2</artifactId><version>build210</version></dependency>
       二、代码实现
package www.gzdx.ssh;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import ch.ethz.ssh2.Connection;import ch.ethz.ssh2.Session;/** * @date 2017年7月28日 */public class SshBasic {    private static final Logger LOGGER = LoggerFactory.getLogger(SshBasic.class);    private Connection conn;    private static SshBasic instance;    private SshBasic() {    }    public static SshBasic getInstance() {        if (instance == null) {            synchronized (SshBasic.class) {                instance = new SshBasic();            }        }        return instance;    }    /**     * 连接ssh服务器     * @param hostname ip地址     * @param username 用户名     * @param password  密码     * @return     */    public Connection connect(String hostname, String username, String password) {        try {            conn = new Connection(hostname);            conn.connect();            boolean isAuthenticated = conn.authenticateWithPassword(username, password);            if (isAuthenticated == false)                throw new IOException("Authentication failed.");            System.out.println("与主机:"+ hostname + "连接成功");        } catch (IOException e) {            System.out.println(e.getMessage() + e);        }        return conn;    }        /**     * 执行命令     * @param command 命令字符串     * @return     */    public boolean execCommand(String command) {        boolean flag = false;        Session sess = null;        BufferedReader br = null;        if (conn == null)             throw new IllegalStateException("没有建立连接");                System.out.println("开始执行命令:" +  command);        int length = -1;        byte[] buffer = new byte[1024];        long start = System.currentTimeMillis();        StringBuilder sb = new StringBuilder();        try {            sess = conn.openSession();            sess.execCommand(command);            InputStream is = sess.getStderr();            while ((length = is.read(buffer)) > -1) {                sb.append(new String(buffer, 0, length));            }            System.out.println(sb.toString()); // 实时打印命令执行情况            flag = true;            System.out.println("命令执行成功,耗时:秒"+ (System.currentTimeMillis() - start) / 1000.0 + "秒");        } catch (IOException e) {            System.out.println(e.getMessage() + e);        } finally {            try {                if (sess != null) {                    sess.close();                }                if (null != br) {                    br.close();                }            } catch (IOException e) {                e.printStackTrace();            }        }        return flag;    }    /**     * 关闭连接     */    public void close() {        if (conn != null) {            conn.close();        }    }    public static void main(String[] args) {        String hostname = "主机ip地址";        String username = "用户名";        String password = "密码";        SshBasic instance = SshBasic.getInstance();        instance.connect(hostname, username, password);        instance.execCommand("scp /home/ueap/3.txt /home/ueap/ftp/");//在服务器上可执行的shell命令        instance.close();    }}


原创粉丝点击