首页 > 编程语言 > 详细

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

时间:2019-11-27 18:31:44      阅读:85      评论:0      收藏:0      [点我收藏+]

导入必要的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连接远程服务器并执行命令

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!