java 运行 linux shell 命令

1)发布到linux服务器上使用

public List runShell(String shell) throws IOException,
			InterruptedException {
		InputStream in = null;
		List resultList = new ArrayList();
		
		log.debug("执行shell脚本: " + shell);
		Runtime run = Runtime.getRuntime();
		Process proc = run.exec(shell);
		Thread th = new Thread() {
			public void run() {
				BufferedReader br = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
				char[] str = new char[100];
				try {
					int n = 0;
					while ((n = br.read(str)) != -1) {
						String s = String.copyValueOf(str, 0, n);
						log.debug("错误输出 : " + s);
						if ( s.indexOf("password:") != -1) {
							PrintWriter out = new PrintWriter(proc.getOutputStream());
							
							out.flush();
							out.close();
						}
					}
				} catch (IOException e) {
					log.error("执行异常:", e);
				}
			}
		};
		th.start();
		int resultValue = proc.waitFor();
		log.debug("命令退出值:" + resultValue);
		if (resultValue != 0) {
			try {
				throw new Exception("命令执行结果不正确");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		/*Process pro = Runtime.getRuntime().exec(shell);
		pro.waitFor();
		*/
		in = proc.getInputStream();
		BufferedReader read = new BufferedReader(new InputStreamReader(in));
		while (true) {

			String line = read.readLine();
			if (line == null) {
				break;
			}
			resultList.add(line);
			log.debug("执行结果: " + line);
		}
		read.close();
		return resultList;

	}
2)远程使用 需要ssh协议

public List runShell2(String shell) throws IOException,
			InterruptedException {
			List resultList = new ArrayList();
			 String hostname = "172.31.114.126";
			   String username = "root";
			    String password = "isoft123@";
			    Connection conn =null;
			    Session sess=null;
			    BufferedReader brs=null;
		    try
		    {
				
				 conn =new Connection(hostname);
				conn.connect();
				 
				  boolean isAuthenticated = conn.authenticateWithPassword(username, password);
				    if (isAuthenticated == false)
				    throw new IOException("Authentication failed.");
		     //Create a session 
		     sess = conn.openSession();
		    //sess.execCommand("uname -a && date && uptime && who");
		    sess.execCommand(shell);
		    log.debug("连接服务器 "+hostname+" ,执行shell:"+shell);
		   
		    InputStream stdout = new StreamGobbler(sess.getStdout());
		     brs = new BufferedReader(new InputStreamReader(stdout));  
	        while(true){  
	        	
	            String line = brs.readLine();  
	            if(line==null){  
	                break;  
	            }  
	            resultList.add(line);
	           
	            log.debug("执行结果: "+line);
	        }  
	       
		    BufferedReader read = new BufferedReader(new InputStreamReader(stdout));
			while (read.ready()) {
				String result = read.readLine();
				//System.out.println("INFO:" + result);
				log.debug("INFO: " + result);
				resultList.add(result);
			}
			read.close();
		     //Show exit status, if available (otherwise "null") 
		    //System.out.println("ExitCode: " + sess.getExitStatus());
		   
		   
		    }
		    catch (IOException e)
		    {
		    e.printStackTrace(System.err); System.exit(2);
		    }finally{
		    	if(brs!=null)
		    	 brs.close();
		    	  //Close this session 
		    	if(sess!=null)
				    sess.close();
				    // Close the connection 
		    	if(conn!=null)
				    conn.close();
		    }
		    return resultList;
	}

在运行 sudo 命令时,会出现问题。需要修改sudo 的配置文件


你可能感兴趣的:(java)