使用JSCH框架通过跳转机访问其他节点的方法
之前搞了套远程访问ssh进行操作的代码,最近有需求,需要通过一台跳转机才能访问目标服务。在网上搜了半天,也没找到比较好的例子,就自己翻阅了下JSCH的API。但是看的云里雾里的。联想了下,端口转发的原理是否是把目标节点ip:port映射到localhost:port,然后通过localhost:port发送消息就可以抵达目标节点呢?
带着这个推论,改造了下之前的代码。
原有代码通过jsch连接目标节点服务器这里就不多说了,自行百度,网上很多。
下面贴下改造之后的代码:
/**
*获取连接
*@paramip跳转机host
*@paramuserName跳转机用户名
*@parampwd跳转机密码
*@paramport跳转机端口
*@returnChannelSftp返回值
*@throwsJSchException连接异常
*/
publicstaticChannelSftpconnect(Stringip,StringuserName,Stringpwd,intport)throwsJSchException
{
if(port<=0)
{
port=PORT;
}
SessionsshSession=null;
JSchjsch=newJSch();
sshSession=jsch.getSession(userName,ip,port);
sshSession.setPassword(pwd);
PropertiessshConfig=newProperties();
sshConfig.put("StrictHostKeyChecking","no");
sshConfig.put("PreferredAuthentications",
"password,keyboard-interactive");
sshSession.setConfig(sshConfig);
sshSession.connect(TMOUT);//可设置超时时间
//此处开始为端口映射到本地的部分
sshSession.setPortForwardingL(本地端口,目标节点地址,22);
//完成上诉映射之后,即可通过本地端口连接了
Sessionsession=jsch.getSession("目标服务用户名","127.0.0.1",本地端口);
PropertiesremoteCfg=newProperties();
remoteCfg.put("StrictHostKeyChecking","no");
remoteCfg.put("PreferredAuthentications",
"password,keyboard-interactive");
session.setConfig(remoteCfg);
session.setPassword("目标服务密码");
session.connect();
//后续如何可自行改变,网上运用很多
Channelchannel=(Channel)session.openChannel("sftp");//创建sftp通信通道
channel.connect();
ChannelSftpsftp=(ChannelSftp)channel;
returnsftp;
}
最后测试通过sftp访问目标节点的目录,成功。
以上这篇使用JSCH框架通过跳转机访问其他节点的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。