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")