码迷,mamicode.com
首页 > 编程语言 > 详细

java连接远程服务器并执行命令

时间:2019-11-27 17:33:03      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:star   host   public   ORC   bash   writer   uil   ash   服务   

导入必要的jar包

  <dependency>
     <groupId>ch.ethz.ganymed</groupId>
    <artifactId>ganymed-ssh2</artifactId>
    <version>build250</version>
  </dependency>

public static void executeCommand(String command,String host,String username,String password){
		Connection conn = null;
		Session session = null;
		try {
			logger.info("执行linux命令:{},host:{}",command,host);
			conn = new Connection(host);
            conn.connect();
            boolean flg = conn.authenticateWithPassword(username, password);
            if(flg){
            	session = conn.openSession();

                session.requestPTY("bash");
                session.startShell();
                PrintWriter out = new PrintWriter(session.getStdin());
                out.println(command);
                out.flush();
                out.println("exit");
                out.close();
                session.waitForCondition(ChannelCondition.CLOSED | ChannelCondition.EOF | ChannelCondition.EXIT_STATUS,
                        60000);
            }else{
            	logger.info("连接host{}失败",host);
            }
		} catch (IOException e) {
			logger.info("host{}执行命令:{}出现异常"+e,host,command);
		}finally {
			session.close(); 
			conn.close();
		}

	}

  

java连接远程服务器并执行命令

标签:star   host   public   ORC   bash   writer   uil   ash   服务   

原文地址:https://www.cnblogs.com/linbky/p/11943879.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!