由于我将oracle和hadoop之间的交互暂时用的是sqoop-1.4.5,也就是sqoop1系列。但是sqoop1系列主要的都是通过命令行的方式来实现oracle与hadoop之间的交互。但是我最初的想法是通过java来操作sqoop,从而实现oracle与hadoop之间的交互工作是全自动化的。通过google和百度,最后找到了有几种方法。但是其最实用的方法就是用sshxcute-1.0来实现执行linux命令行的方法。下面主要将其过程记录一下:
要使用sshxcute-1.0,必须在http://code.google.com/p/sshxcute/网上下载sshxcute-1.0.jar包。但是由于大陆将google封了,无法访问,最后通过亚峰利用VPN技术来实现下载。
下载好后,直接将jar包添加到对应的工程目录下即可。
下面通过一个示例来测试其强大的功能:请看下面的代码:
public static void main(String[] args) {
// TODO Auto-generated method stub
// Initialize a ConnBean object, parameter list is ip, username,
ConnectWithSSH test =new ConnectWithSSH();
String ip="192.168.1.21";
String username="grid";
String passwd="liujiyu";
String command="ls /home";
test.ConnectSSH(ip, username, passwd, command);
}
import net.neoremind.sshxcute.core.ConnBean; import net.neoremind.sshxcute.core.SSHExec; import net.neoremind.sshxcute.task.CustomTask; import net.neoremind.sshxcute.task.impl.ExecCommand; public class ConnectWithSSH { public void ConnectSSH(String ServerIP,String username,String password,String command ){ ConnBean cb = new ConnBean(ServerIP, username, password); SSHExec ssh = null; try { // Put the ConnBean instance as parameter for SSHExec static method // getInstance(ConnBean) to retrieve a singleton SSHExec instance ssh = SSHExec.getInstance(cb); // Connect to server ssh.connect(); //执行的命令行任务 CustomTask sampleTask = new ExecCommand(command); //执行,并对执行后的结果进行处理 net.neoremind.sshxcute.core.Result res = ssh.exec(sampleTask); // Check result and print out messages. if (res.isSuccess) { System.out.println("Return code: " + res.rc); System.out.println("sysout: " + res.sysout); } else { System.out.println("Return code: " + res.rc); System.out.println("error message: " + res.error_msg); } } catch (Exception e) { e.printStackTrace(); } finally { ssh.disconnect(); } } }
以上代码执行完之后结果为:
SSHExec initializing ... Session initialized and associated with user credential liujiyu SSHExec initialized successfully SSHExec trying to connect grid@192.168.1.21 SSH connection established Command is ls /home Connection channel established succesfully Start to run command grid
这里需要注意一个问题:通过远程连接到linux主机上时,在执行命令时,命令前面已经是他的完全路径,不能是简单的一个命令,否则会出现不认识在该命令。如
CustomTask sampleTask1 = new ExecCommand(" /home/grid/sqoop-1.4.5/bin/sqoop help")
或者在执行该命令之前,执行source /etc/profile。但是要注意这句话要跟所要执行的命令一起放在一起,用分号隔开。如下所示: (如果两个命令不放在一起,将会出现原来同样的错误)
CustomTask sampleTask1 = new ExecCommand(" source /etc/profile; sqoop help")
浙公网安备 33010602011771号