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 user2@10.196.21.130:/home/user2/.ssh/id_dsa.pub ###复制公钥到21.130
ssh dsam@10.196.21.130 ##输入密码
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 user2@10.196.21.130 ##进行连接测试
以上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;
}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值