<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>build210</version>
</dependency>
package cn.tisson.ipran.gdcsgcf.driver.client;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.ServerHostKeyVerifier;
import ch.ethz.ssh2.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class SshCommandDriver extends CommandDriver{
protected Logger log = LoggerFactory.getLogger(SshCommandDriver.class);
private Connection conn = null;
//SSH会话
private Session sess = null;
@Override
public int open(String ip, int port, String loginPrompt, String userName,
String pwdPrompt, String pwd, String commandPrompt,StringBuffer resultBuf) {
if (isOpen) {
log.debug("SSH 连接已经打开 ");
return 0;
}
if (ip == null || ip.equals("") || port < -1) {
log.error("需要ssh连接的ip 或端口不正确,请校验");
resultBuf.append("需要ssh连接的ip 或端口不正确,请校验");
return -101;
}
try {
this.ip=ip;
conn = new Connection(ip, port);
conn.connect(new ServerHostKeyVerifier() {
@Override
public boolean verifyServerHostKey(String hostname, int port,
String serverHostKeyAlgorithm, byte[] serverHostKey)
throws Exception {
return true;
}
}, 5000, 30000);
} catch (Exception e) {
resultBuf.append(e.getMessage());
log.error(ip + " 打开SSH 连接出现异常,连接ip端口为" + port, e);
close();
return -102;
}
boolean isAuthentication = false;
try {
isAuthentication = conn.authenticateWithPassword(userName,pwd);
} catch (Exception e) {
resultBuf.append(e.getMessage());
log.error(ip + " SSH授权出现异常,连接ip端口为"+ port, e);
close();
return -103;
}
if (!isAuthentication) {
resultBuf.append(ip + " SSH授权失败,连接ip端口为" + port);
log.error(ip + " SSH授权失败,连接ip端口为" + port);
close();
return -104;
}
try {
sess = conn.openSession();
sess.requestPTY("dumb", 132, 90, 0, 0, null);
sess.startShell();
} catch (Exception e) {
resultBuf.append(e.getMessage());
close();
log.error(ip + "获取session出现异常,连接ip端口为" + port,e);
return -105;
}
try {
isr = new InputStreamReader(sess.getStdout(), charsetName);
osr = new OutputStreamWriter(sess.getStdin(), charsetName);
} catch (Exception e) {
resultBuf.append(e.getMessage());
close();
log.error(ip + "获取输入/出流出现异常,连接ip端口为" + port,e);
return -106;
}
try {
String result=read(commandPrompt);
resultBuf.append(result);
if(this.isAutoAnswer){
this.write("N");
result=read(commandPrompt);
resultBuf.append(result);
}
log.debug(result);
this.commandPrompt=result.substring(result.lastIndexOf("\n")+1);
} catch (Exception e) {
resultBuf.append(e.getMessage());
log.error("读取数据出现异常",e);
}
this.isOpen = true;
return 0;
}
public void close(){
super.close();
try {
if (sess != null) {
sess.close();
}
if (conn != null) {
conn.close();
}
} catch (Exception e) {
log.error(ip+" closed sshClient exception", e);
}finally{
sess=null;
conn = null;
}
}
public static void main(String [] args) throws Exception{
SshCommandDriver d=new SshCommandDriver();
StringBuffer buf = new StringBuffer();
int result=d.open("*.*.*.*", 22, ":", "admin", ":", "123@abc", ">",buf);
System.out.println(result);
if(result==0){
d.write("display version");
String temp=d.read();
System.out.println(temp);
}
d.close();
}
}
package cn.tisson.ipran.gdcsgcf.driver.client;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public abstract class CommandDriver implements ICommandDriver{
protected Logger log = LoggerFactory.getLogger(CommandDriver.class);
protected InputStreamReader isr;// 输入流
protected OutputStreamWriter osr;// 输出流
protected boolean isOpen = false;// 是否已经打开连接,防止打开多次
protected String ip;
protected String userName;
protected String pwd;
protected String commandPrompt;
protected String loginPrompt;
protected String pwdPrompt;
protected int outTime=10000;
protected String charsetName="iso8859-1";
protected String neName;
protected boolean isAutoAnswer = false;
public boolean isAutoAnswer() {
return isAutoAnswer;
}
@Override
public abstract int open(String ip, int port, String loginPrompt, String userName,
String pwdPrompt, String pwd, String commandPrompt,StringBuffer resultBuf);
@Override
public void close() {
this.isOpen = false;
try {
if (isr != null) {
isr.close();
}
} catch (IOException e) {
log.error(this.ip + "closed inputStreamRead failed", e);
} finally {
isr = null;
}
try {
if (osr != null) {
osr.close();
}
} catch (IOException e) {
log.error(this.ip + "closed outputStramRead failed", e);
} finally {
osr = null;
}
}
@Override
public void write(String command) throws Exception {
log.debug(ip+" 发送的命令为"+command);
clearReadBuffer();
osr.write(command+ getTerminalSendPostfix());
osr.flush();
}
@Override
public void write(String command,String terminalSendPostfix) throws Exception {
log.debug(ip+" 发送的命令为"+command);
clearReadBuffer();
osr.write(command+ terminalSendPostfix);
osr.flush();
}
@Override
public String read() throws Exception {
return this.read(new StringResponseEndChecker() {
@Override
public boolean isResponseEnd(StringBuffer data) {
if (data!=null&&data.toString().trim().endsWith(commandPrompt)) {
return true;
}
return false;
}
}, this.outTime);
}
@Override
public String read(String terminator) throws Exception {
return this.read(terminator, this.outTime);
}
@Override
public String read(final String terminator,int timeout) throws Exception {
return this.read(new StringResponseEndChecker() {
@Override
public boolean isResponseEnd(StringBuffer data) {
if (data!=null&&data.toString().trim().endsWith(terminator)) {
return true;
}else if(data!=null&&data.toString().trim().endsWith("[Y/N]:")){
isAutoAnswer=true;
return true;
}
return false;
}
}, timeout);
}
public boolean isOpen(){
return this.isOpen;
}
@Override
public void setCharsetName(String charsetName) {
if(charsetName!=null)
this.charsetName=charsetName;
}
@Override
public String getUsername() {
return this.userName;
}
@Override
public String getPassword() {
return this.pwd;
}
@Override
public String getNeName() {
return this.neName;
}
/** * 清空接受 */ private void clearReadBuffer() {
BufferedReader br = null;
try {
if (isr!=null) {
br = new BufferedReader(isr);
while (br.ready()) {
br.read();
}
}
} catch (Exception e) {
log.error("清空read buffer 出现异常", e);
}
}
/** * 命令发送结尾符 * @return */ protected String getTerminalSendPostfix() {
return "\r\n";
}
@Override
public String read(StringResponseEndChecker checker, long timeout) throws IOException{
long time = System.currentTimeMillis() + timeout;
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
boolean readed = false;
boolean isClose=true;//用来判断网络是否正常 true不正常 false正常
br = new BufferedReader(isr);
while (System.currentTimeMillis() < time) {
try {
if (br.ready()) {
int brchar = br.read();
if((32<=brchar&&brchar<=127)||brchar==10||brchar==13) {
sb.append((char) brchar);
}
readed = true;
isClose=false;
} else {
if ((checker != null) && (readed == true)) {
readed = false;
if (checker.isResponseEnd(sb))
break;
}
Thread.sleep(150);
}
} catch (InterruptedException e) {
log.error("读取数据出现异常",e);
}
}
if(isClose&&sb.length()==0){
this.isOpen=false;
throw new IOException("网络已经中断.....");
}
String temp=sb.toString();
// temp=temp.substring(temp.indexOf("\n")+1);//删除命令回显
log.debug(ip+" 接受到的数据为"+temp);
return temp;
}
@Override
public void setOutTime(int outTime) {
if(outTime>5000)
this.outTime = outTime;
}
@Override
public int getOutTime() {
return outTime;
}
}
package cn.tisson.ipran.gdcsgcf.driver.client;
public interface ICommandDriver {
public boolean isAutoAnswer();
/** * 打开连接 * @param ip telnet ip地址 如127.0.0.1 * @param port telnet 端口号 如23 * @param loginPrompt 用户名输入提示符 如userName: * @param userName 用户名 如who * @param pwdPrompt 输入密码提示符 如Password: * @param pwd 密码 如who * @param commandPrompt 登陆成功提示符 如> * @return 0成功,-1数据可是不对 -2没有接到输入用户名提示符 -3没有接收到密码提示符 -4没有接到登陆成功提示符 -5出现异常 */ public abstract int open(String ip, int port, String loginPrompt,String userName, String pwdPrompt, String pwd, String commandPrompt,StringBuffer resultBuf);
/** * 关闭连接 */ public void close();
/** * 获取登录用户名 * @return */ public String getUsername();
/** * 获取登录密码 * @return */ public String getPassword();
/** * 获取网元名称 * @return */ public String getNeName();
/** * 发送命令 * @param command * @throws Exception */ public void write(String command) throws Exception;
/** * 发送命令 * @param command * @param terminalSendPostfix \r\n \r * @throws Exception */ public void write(String command,String terminalSendPostfix) throws Exception;
/** * 接受命令结果 * @return * @throws Exception */ public String read() throws Exception;
/** * 接受命令结果直到结束 * @param terminator * @return * @throws Exception */ public String read(String terminator)throws Exception;
/** * 设置字符集 * @param charsetName */ public void setCharsetName(String charsetName);
/** * @param terminator * @param timeout * @return * @throws Exception */ String read(String terminator, int timeout) throws Exception;
/** * 返回连接状态 主要是主动关闭 */ public boolean isOpen();
/** * 设置默认超时时间单位毫秒 * @param outTime */ public void setOutTime(int outTime);
public int getOutTime();
String read(StringResponseEndChecker checker, long timeout) throws Exception;
}
还没有评论,来说两句吧...