Blog信息 |
blog名称: 日志总数:1304 评论数量:2242 留言数量:5 访问次数:7584150 建立时间:2006年5月29日 |

| |
[J2SE]在java程序里telnet到远端设备执行命令 软件技术
lhwork 发表于 2006/12/28 9:06:44 |
kelefa是某公司的一个程序员,传说他是一流的程序员,开发了一个系统非常稳定,从来没有出现过问题,当然这世界上没有完美的人,也没有完美的软件,
这个系统也有bug,而且他已经发现了,但是一直没有找到很好的办法解决,还好这个bug很少有机会能发作,关键是一发生这种情况时严重影响系统的运行,
停止服务后再重新启动是目前最好的方法。 为了保住“高手”的称号,他又搞了一个监控该系统的小程序,能及时发现系统是否工作正常,如果发现异常情况立刻发送email给自己,email又跟自己的手机短信绑定,使他能迅速的发现情况并跑到电脑前:500)this.width=500'>//telnet进来后500)this.width=500'>[root@kelefa root]$ su -500)this.width=500'>[root@kelefa root]$ password 500)this.width=500'>[root@kelefa root]# cd /usr/local/resin-3.0.14/bin500)this.width=500'>[root@kelefa bin]# ./httpd.sh stop500)this.width=500'>[root@kelefa bin]# ./httpd.sh start一切又正常了,1分钟内搞定,一流程序员再次得到验证,可是email有时会发送失败,sp的短信也不是绝对的正常,而且每个月还给n元大洋给sp,万一收到告警短信旁边没有电脑也无能为力。 终于发现更好的方法:在监控程序里直接telnet到设备上进行操作,动手前当然要看看有什么开源的可以利用,它就是Jakarta的Commons Net,这个包支持ftp,telnet,pop3,smtp,nntp等协议。 首先实现一个telnet的基类,它有个connectAndDocommad()的方法,实现链接到指定的设备上,并启动一个线程执行一个模板方法(某设计模式):500)this.width=500'> // 登陆 log.debug( "login................" ); if ( false == login() ) { String msg = new Date().toString() + " telnet登陆不成功,ip:" + remoteip; log.warn( msg ); SyslogUtil.send( msg ); return; } log.debug( "doCommand................" ); // 抽象方法 doCommand(); // 退出 log.debug( "exit................" ); exit(); 其次类RestartTask继承该抽象类,实现doCommand()抽象方法,往输出流发送操作命令,实现重启:500)this.width=500'>@Override protected void doCommand() { log.debug( "resin restart................" ); try { writeLine("su -"); writeLine("password"); writeLine("cd /usr/local/resin-3.0.14/bin"); writeLine("./httpd.sh stop"); writeLine("./httpd.sh start"); readResult(); } catch ( IOException e ) { log.warn( e.getMessage() ); } }以上为伪代码,需要实现一些子方法, 如有雷同,纯属虚构! |
|
|