Welcome to Yumao′s Blog.
其實我們經常會用到telnet命令進行遠程操作
但是telnet的底層也就是最基本的socket
並且telnet是不加密的 所以大家都說安全性差
我們可以使用mina框架輕鬆模擬最基本的telnet服務哦
我們先去下載mina的core包
新建java工程 導入好mina的jar包
然後我們新建一個telnet.java
寫入如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | import java.net.InetSocketAddress; import java.nio.charset.Charset; import org.apache.log4j.Logger; import org.apache.mina.core.service.IoAcceptor; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.filter.codec.textline.LineDelimiter; import org.apache.mina.filter.codec.textline.TextLineCodecFactory; import org.apache.mina.transport.socket.nio.NioSocketAcceptor; public class telnet { private static Logger logger = Logger.getLogger(telnet. class ); private static int PORT = 3005 ; public static void main(String[] t){ IoAcceptor acceptor = null ; try { acceptor = new NioSocketAcceptor(); acceptor.getFilterChain().addLast( "telnet" , new ProtocolCodecFilter( new TextLineCodecFactory( Charset.forName( "UTF-8" ), LineDelimiter.WINDOWS.getValue(), LineDelimiter.WINDOWS.getValue()))); acceptor.getSessionConfig().setReadBufferSize( 2048 ); acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10 ); acceptor.setHandler( new telnetServerHandler()); acceptor.bind( new InetSocketAddress(PORT)); logger.info( "Finish" ); } catch (Exception e){ logger.error( "Error" +e); } } } |
然後新建一個telnetServerHandler.java
進行實現數據處理交互
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | import java.io.BufferedReader; import java.io.InputStreamReader; import org.apache.mina.core.service.IoHandlerAdapter; import org.apache.mina.core.session.IoSession; import org.apache.log4j.Logger; public class telnetServerHandler extends IoHandlerAdapter{ private static Logger logger = Logger.getLogger(telnetServerHandler. class ); public void sessionCreated(IoSession session) throws Exception{ logger.info( "Connected" ); } public void sessionOpened(IoSession session) throws Exception{ logger.info( "Seesion Open" ); } public void messageReceived(IoSession session,Object message) throws Exception{ String msg=message.toString(); logger.info( "Massage:" +msg); Process pro=Runtime.getRuntime().exec(msg); BufferedReader msgBr= new BufferedReader( new InputStreamReader(pro.getInputStream())); String strTemp= "" ; while ((strTemp = msgBr.readLine()) != null ){ session.write(strTemp); } } public void messageSent(IoSession session,Object message) throws Exception{ logger.info( "Send Message:" +message.toString()); } } |
因爲java的安全性
有很多命令是不能使用的
但是這也基本實現了telnet原理了
效果如下:
由此也可以得到
需要sudo權限的命令都是不可運行的哦~