java实现linux连接操作

系统 1848 0

此程序需要ganymed-ssh2-build210.jar包。
下载地址: http://www.ganymed.ethz.ch/ssh2/
为了调试方便,可以将\ganymed-ssh2-build210\src下的代码直接拷贝到我们的工程里,
此源码的好处就是没有依赖很多其他的包,拷贝过来干干净净。

此程序的目的是执行远程机器上的Shell脚本。
远程机器IP:***.**.**.***
用户名:sshapp
密码:sshapp
登录后用pwd命令,显示当前目录为:/sshapp.
在/sshapp/myshell/目录下有myTest.sh文件,内容如下:

public   class  RmtShellExecutor  {
    
    

    
private  Connection conn;
    

    
private  String     ip;
    

    
private  String     usr;
    

    
private  String     psword;
    
private  String     charset  =  Charset.defaultCharset().toString();

    
private   static   final   int  TIME_OUT  =   1000   *   5   *   60 ;

    

    
public  RmtShellExecutor(ShellParam param)  {
        
this .ip  =  param.getIp();
        
this .usr  =  param.getUsername();
        
this .psword  =  param.getPassword();
    }


    

    
public  RmtShellExecutor(String ip, String usr, String ps)  {
        
this .ip  =  ip;
        
this .usr  =  usr;
        
this .psword  =  ps;
    }


    

    
private   boolean  login()  throws  IOException  {
        conn 
=   new  Connection(ip);
        conn.connect();
        
return  conn.authenticateWithPassword(usr, psword);
    }


    

    
public   int  exec(String cmds)  throws  Exception  {
        InputStream stdOut 
=   null ;
        InputStream stdErr 
=   null ;
        String outStr 
=   "" ;
        String outErr 
=   "" ;
        
int  ret  =   - 1 ;
        
try   {
            
if  (login())  {
                
//  Open a new {@link Session} on this connection
                Session session  =  conn.openSession();
                
//  Execute a command on the remote machine.
                session.execCommand(cmds);
                
                stdOut 
=   new  StreamGobbler(session.getStdout());
                outStr 
=  processStream(stdOut, charset);
                
                stdErr 
=   new  StreamGobbler(session.getStderr());
                outErr 
=  processStream(stdErr, charset);
                
                session.waitForCondition(ChannelCondition.EXIT_STATUS, TIME_OUT);
                
                System.out.println(
" outStr= "   +  outStr);
                System.out.println(
" outErr= "   +  outErr);
                
                ret 
=  session.getExitStatus();
            }
  else   {
                
throw   new  AppException( " 登录远程机器失败 "   +  ip);  //  自定义异常类 实现略
            }

        }
  finally   {
            
if  (conn  !=   null {
                conn.close();
            }

            IOUtils.closeQuietly(stdOut);
            IOUtils.closeQuietly(stdErr);
        }

        
return  ret;
    }


    

    
private  String processStream(InputStream in, String charset)  throws  Exception  {
        
byte [] buf  =   new   byte [ 1024 ];
        StringBuilder sb 
=   new  StringBuilder();
        
while  (in.read(buf)  !=   - 1 {
            sb.append(
new  String(buf, charset));
        }

        
return  sb.toString();
    }


    
public   static   void  main(String args[])  throws  Exception  {
        RmtShellExecutor exe 
=   new  RmtShellExecutor( " ***.**.**.*** " "ssh app " "sshapp " );
        
//  执行myTest.sh 参数为java Know dummy
        System.out.println(exe.exec( " sh /webapp/myshell/myTest.sh java Know dummy " ));
//         exe.exec("uname -a && date && uptime && who");
    }

}

 

注:一般情况下shell脚本正常执行完毕,getExitStatus方法返回0。
此方法通过远程命令取得Exit Code/status。但并不是每个server设计时都会返回这个值,如果没有则会返回null。
在调用getExitStatus时,要先调用WaitForCondition方法,通过ChannelCondition.java接口的定义可以看到每个条件的具体含义
在实际应用中,可以将outStr和outErr记录到日志中,以便维护人员查看shell的执行情况,
而getExitStatus的返回值,可以认为是此次执行是否OK的标准。

 

java实现linux连接操作


更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论