ssh java类的连接与远程命令执行(包括密钥连接)

ssh java类的连接与远程命令执行(包括密钥连接)
首先先介绍ssh的密钥连接(lunix):
例:10.196.20.4(user1/1234)服务器建立-- 10.196.21.130(user2/1234)服务器的密钥连接
1. 在10.196.20.4服务器上生产公密钥文件
ssh-keygen –t dsa ###在$home/.ssh文件下会生成id_dsa.pub 和id_dsa文件
chmod –R 700 /home/user1/.ssh
chmod –R 600 /home/user1/.ssh/authorized_keys
scp id_dsa.pub [email protected]:/home/user2/.ssh/id_dsa.pub ###复制公钥到21.130
ssh [email protected] ##输入密码
cd /home/dsadm/.ssh
cat id_dsa.pub >> authorized_keys
chmod –R 700 /home/user2/.ssh
chmod –R 600 /home/user2/.ssh/authorized_keys
exit ##退出21.130 进入20.4
ssh [email protected] ##进行连接测试
以上20.4中的id_dsa 就是密钥文件,可以放在任何服务器上密钥连接21.130

使用:ganymed-ssh-2-build260.jar
package com.zgs.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

/**
*
* @author Administrator
* 2015-4-11
*
*/
public class SSHConnect {

private String hostName;
private String userName;
private String password;
private int port;
private File pemFile;
Connection conn=null;
/**
* @param hostName
* @param userName
* @param password
*/
public SSHConnect(String hostName, String userName, String password) {
super();
this.hostName = hostName;
this.userName = userName;
this.password = password;
}

public boolean passConnect()throws Exception{
conn=new Connection(hostName);
conn.connect();
boolean isAuthenticated =conn.authenticateWithPassword(userName, password);
return isAuthenticated;
}

public boolean publicKeyConnect()throws Exception{
conn=new Connection(hostName);
conn.connect();
boolean isAuthenticated =conn.authenticateWithPublicKey(userName,pemFile, password);
return isAuthenticated;
}


public List execCommand(String command){
try {
if(!passConnect()){
if(!publicKeyConnect()){
throw new Exception("连接配置有问题哟!");
}
}
Session session=conn.openSession();
session.execCommand(command);
InputStream stdout=new StreamGobbler(session.getStdout());
BufferedReader br=new BufferedReader(new InputStreamReader(stdout));
List list=null;
String line;
while((line=br.readLine())!=null){
list.add(line);
}
return list;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}

你可能感兴趣的:(Java,EE)