java 连接Linux服务器并执行指令

 
 
  1. /** 
  2.  * Created by hpp on 2017/6/5. 
  3.  */  
  4.   
  5. import ch.ethz.ssh2.Connection;  
  6. import ch.ethz.ssh2.Session;  
  7. import ch.ethz.ssh2.StreamGobbler;  
  8. import com.lczyfz.istep.common.utils.StringUtils;  
  9.   
  10. import java.io.*;  
  11.   
  12. /** 
  13.  * 远程执行linux的shell script 
  14.  * @author Ickes 
  15.  * @author2 hpp 
  16.  * @since  V0.2 
  17.  */  
  18. public class RemoteExecuteCommand {  
  19.     //字符编码默认是utf-8  
  20.     private static String  DEFAULTCHART="UTF-8";  
  21.     private static Connection conn;  
  22.     private String ip;  
  23.     private String userName;  
  24.     private String userPwd;  
  25.   
  26.     public RemoteExecuteCommand(String ip, String userName, String userPwd) {  
  27.         this.ip = ip;  
  28.         this.userName = userName;  
  29.         this.userPwd = userPwd;  
  30.     }  
  31.   
  32.     public RemoteExecuteCommand() {  
  33.   
  34.     }  
  35.   
  36.     /** 
  37.      * 远程登录linux的主机 
  38.      * @author Ickes 
  39.      * @since  V0.1 
  40.      * @return 
  41.      *      登录成功返回true,否则返回false 
  42.      */  
  43.     public Boolean login(){  
  44.         boolean flg=false;  
  45.         try {  
  46.             conn = new Connection(ip);  
  47.             conn.connect();//连接  
  48.             flg=conn.authenticateWithPassword(userName, userPwd);//认证  
  49.             if (flg){  
  50.                 System.out.println("认证成功!");  
  51.             }  
  52.         } catch (IOException e) {  
  53.             e.printStackTrace();  
  54.         }  
  55.         return flg;  
  56.     }  
  57.     /** 
  58.      * @author Ickes 
  59.      * 远程执行shll脚本或者命令 
  60.      * @param cmd 
  61.      *      即将执行的命令 
  62.      * @return 
  63.      *      命令执行完后返回的结果值 
  64.      * @since V0.1 
  65.      */  
  66.     public String execute(String cmd){  
  67.         String result="";  
  68.         try {  
  69.             if(login()){  
  70.                 Session session= conn.openSession();//打开一个会话  
  71.                 session.execCommand(cmd);//执行命令  
  72.                 result=processStdout(session.getStdout(),DEFAULTCHART);  
  73.                 //如果为得到标准输出为空,说明脚本执行出错了  
  74.                 if(StringUtils.isBlank(result)){  
  75.                     result=processStdout(session.getStderr(),DEFAULTCHART);  
  76.                 }  
  77.                 conn.close();  
  78.                 session.close();  
  79.             }  
  80.         } catch (IOException e) {  
  81.             e.printStackTrace();  
  82.         }  
  83.         return result;  
  84.     }  
  85.   
  86.   
  87.     /** 
  88.      * @author Ickes 
  89.      * 远程执行shll脚本或者命令 
  90.      * @param cmd 
  91.      *      即将执行的命令 
  92.      * @return 
  93.      *      命令执行成功后返回的结果值,如果命令执行失败,返回空字符串,不是null 
  94.      * @since V0.1 
  95.      */  
  96.     public String executeSuccess(String cmd){  
  97.         String result="";  
  98.         try {  
  99.             if(login()){  
  100.                 Session session= conn.openSession();//打开一个会话  
  101.                 session.execCommand(cmd);//执行命令  
  102.                 result=processStdout(session.getStdout(),DEFAULTCHART);  
  103.                 conn.close();  
  104.                 session.close();  
  105.             }  
  106.         } catch (IOException e) {  
  107.             e.printStackTrace();  
  108.         }  
  109.         return result;  
  110.     }  
  111.   
  112.     /** 
  113.      * 解析脚本执行返回的结果集 
  114.      * @author Ickes 
  115.      * @param in 输入流对象 
  116.      * @param charset 编码 
  117.      * @since V0.1 
  118.      * @return 
  119.      *       以纯文本的格式返回 
  120.      */  
  121.     public static String processStdout(InputStream in, String charset){  
  122.         InputStream    stdout = new StreamGobbler(in);  
  123.         StringBuffer buffer = new StringBuffer();;  
  124.         try {  
  125.             BufferedReader br = new BufferedReader(new InputStreamReader(stdout,charset));  
  126.             String line=null;  
  127.             while((line=br.readLine()) != null){  
  128.                 buffer.append(line+"\n");  
  129.             }  
  130.         } catch (UnsupportedEncodingException e) {  
  131.             e.printStackTrace();  
  132.         } catch (IOException e) {  
  133.             e.printStackTrace();  
  134.         }  
  135.         return buffer.toString();  
  136.     }  
  137.   
  138.   
  139.   
  140.     public static void main(String[] args) {  
  141.   
  142.         RemoteExecuteCommand rec=new RemoteExecuteCommand("xx.xx.xx.xx""root","root");  
  143.         //执行命令  
  144.         try {  
  145.             if(rec.login()){  
  146.   
  147.                 System.out.println("=====第一个步骤=====");  
  148.                 Session session= conn.openSession();//打开一个会话  
  149.                 //TODO:多条命令  
  150.                 session.execCommand("cd /home/ubuntu/Desktop/music_rec/user_sim;echo \"123\" | sudo  -S ./caculate_tim_sim.sh similar");//执行命令  
  151.                 String result=processStdout(session.getStdout(),DEFAULTCHART);  
  152.                 //如果为得到标准输出为空,说明脚本执行出错了  
  153.                 if(StringUtils.isBlank(result)){  
  154.                     System.out.println("脚本出错");  
  155.                     result=processStdout(session.getStderr(),DEFAULTCHART);  
  156.                 }  
  157.                 System.out.println(result);  
  158.                 session.close();  
  159.   
  160.                 System.out.println("=====第二个步骤=====");  
  161.                 Session session2= conn.openSession();//打开一个会话  
  162.                 //TODO:多条命令  
  163.                 session2.execCommand("cd /home/ubuntu/Desktop/music_rec/user_sim/result;cat xyy_result_m10d.json");//执行命令  
  164.                 String result2=processStdout(session2.getStdout(),DEFAULTCHART);  
  165.                 //如果为得到标准输出为空,说明脚本执行出错了  
  166.                 if(StringUtils.isBlank(result2)){  
  167.                     System.out.println("脚本出错");  
  168.                     result2=processStdout(session2.getStderr(),DEFAULTCHART);  
  169.                 }  
  170.                 System.out.println(result2);  
  171.                 session2.close();  
  172.   
  173.   
  174.                 conn.close();  
  175.             }  
  176.         } catch (IOException e) {  
  177.             e.printStackTrace();  
  178.         }  
  179.   
  180.     }  
  181.   
  182.   
  183.   
  184.     public static void setCharset(String charset) {  
  185.         DEFAULTCHART = charset;  
  186.     }  
  187.     public Connection getConn() {  
  188.         return conn;  
  189.     }  
  190.     public void setConn(Connection conn) {  
  191.         this.conn = conn;  
  192.     }  
  193.     public String getIp() {  
  194.         return ip;  
  195.     }  
  196.     public void setIp(String ip) {  
  197.         this.ip = ip;  
  198.     }  
  199.     public String getUserName() {  
  200.         return userName;  
  201.     }  
  202.     public void setUserName(String userName) {  
  203.         this.userName = userName;  
  204.     }  
  205.     public String getUserPwd() {  
  206.         return userPwd;  
  207.     }  
  208.     public void setUserPwd(String userPwd) {  
  209.         this.userPwd = userPwd;  
  210.     }  
  211. }  

猜你喜欢

转载自blog.csdn.net/messinine/article/details/80295889