java 运行 linux shell 命令

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

public List<String> runShell(String shell) throws IOException,
			InterruptedException {
		InputStream in = null;
		List<String> resultList = new ArrayList<String>();
		
		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<String> runShell2(String shell) throws IOException,
			InterruptedException {
			List<String> resultList = new ArrayList<String>();
			 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 的配置文件


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值