首先在远程服务器上编写一个测试脚本test.sh,并赋予可执行权限:chmod +x test.sh

#!/bin/bash
echo $1
$1是脚本传进来的第一个参数,现在打印一下传进来的第一个参数。

在pom中添加依赖

  1. <dependency>  
  2.     <groupId>org.jvnet.hudson</groupId>  
  3.     <artifactId>ganymed-ssh2</artifactId>  
  4.     <version>build210-hudson-1</version>  
  5. </dependency>  
创建工具类

package cn.ctyun.audit.utils;
import java.io.IOException;  
import java.io.InputStream;  
import java.nio.charset.Charset;  
  
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(String ipAddr, String userName, String password,  
	            String charset) {  
	        this.ipAddr = ipAddr;  
	        this.userName = userName;  
	        this.password = password;  
	        if (charset != null) {  
	            this.charset = charset;  
	        }  
	    }  
	    
	    public boolean login() throws IOException {  
	        conn = new Connection(ipAddr);  
	        conn.connect(); // 连接  
	        return conn.authenticateWithPassword(userName, password); // 认证  
	    }  
	    
	    public boolean exec(String cmds) {  
	        InputStream in = null;  
	        String result = ""; 
	        boolean flag = false;
	        try {  
	            if (this.login()) {  
	                Session session = conn.openSession(); // 打开一个会话  
	                session.execCommand(cmds);  
	                in = session.getStdout();  
	                result = this.processStdout(in, this.charset);  
	                session.close();  
	                conn.close(); 
	                flag = true;	            }  
	        } catch (IOException e1) {  
	            e1.printStackTrace();  
	        }  
	        return flag;  
	    }  
	    
	    public String processStdout(InputStream in, String charset) {  
	      
	        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) {  
	  
	        RemoteShellTool tool = new RemoteShellTool("hdp03", "root",  
	                "hadoop", "utf-8");  
		
	        boolean exec = tool.exec("/root/apps/jdk1.7.0_67/bin/java -jar AuditService.jar ");
	        System.out.print(exec);  
	  
	    }  
}
注意:如果要执行jar命令需要写jdk的全路径,否则会找不到java的环境变量!

如果不想输入密码,可以参考下面的文章

点击打开链接



Logo

更多推荐