Jav程序执行Linux命令

方法一:

本地执行,也是是代码必须放在Lunix服务器上才能通过java代码执行Linux命令。

package com.xdja.dsc.common.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * @ClassName: ExecuteLinuxCommandUtils
 * @Description: 执行Linux命令工具类
 * @author niugang
 * @date 2018年8月30日
 */
public class ExecuteLinuxCommandUtils {

	private static Logger logger = 
 LoggerFactory.getLogger(ExecuteLinuxCommandUtils.class);
    	/**
	 * 执行命令如:<br>
	 * cd /usr/local/openresty/nginx/conf/ngx_conf/ && tar czf /tmp/ngx.tar.gz  * <br>
	 * cp /usr/local/openresty/nginx/conf/nginx.conf  /tmp <br>
	 * @param command:执行命令
	 * @return    
	 * @author niugang
	 * @date 2018年8月30日
	 * @throws NullPointerException
	 */
	public static String exc(String command) {
        String result = null;
		Process ps = null;
		BufferedReader br = null;
		try {
			if (command == null || "".equals(command)) {
				throw new NullPointerException("command is not null");
			}
			List<String> comList = new ArrayList<String>(3);
			comList.add("/bin/sh");
			comList.add("-c");
			comList.add(command);
			logger.info("execute command is:{}", comList.toString());
			String[] commandArray = comList.toArray(new String[comList.size()]);
			ps = Runtime.getRuntime().exec(commandArray);
			ps.waitFor();
            br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
			StringBuffer sb = new StringBuffer();
			String line;
			while ((line = br.readLine()) != null) {
				sb.append(line).append("\n");
			}
			result = sb.toString();
			br.close();
			logger.info("execute linux command result:{}", result);
		} catch (Exception ex) {
			logger.error("execute linux command error:{}", ex);
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}

}

方法二:远程连接

pom.xml

<!--操作ssh  -->
<dependency>
	<groupId>com.jcraft</groupId>
	<artifactId>jsch</artifactId>
	<version>0.1.50</version>
</dependency>

代码:

package com.xdja.dsc;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import com.jcraft.jsch.ChannelShell;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

/**
 * 
 * @ClassName: TestSsh
 * @Description: ssh测试
 * @author niugang
 * @date 2018年8月28日
 */

public class TestSsh {

	/**
	 * 远程执行JSch
	 * @param args
	 * @throws JSchException
	 * @throws IOException    
	 * @author niugang
	 * @date 2018年8月30日
	 * @throws
	 */
public static void main(String[] args) throws JSchException, IOException {
		JSch jsch = new JSch();
		Session session = jsch.getSession("root", "11.12.115.206", 22);
		session.setPassword("123456");
		session.setConfig("StrictHostKeyChecking", "no");
		session.setConfig("userauth.gssapi-with-mic", "no");
		session.connect();
		ChannelShell channel = (ChannelShell) session.openChannel("shell");
		channel.connect();
		InputStream inputStream = channel.getInputStream();
		OutputStream outputStream = channel.getOutputStream();

		String cmd2 = "cd /home/xdja \n\r";
		outputStream.write(cmd2.getBytes());
		String cmd = "ll \n\r";
		outputStream.write(cmd.getBytes());
		outputStream.flush();
		BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));

		String msg = null;
		while ((msg = in.readLine()) != null) {
			String encoding = getEncoding(msg);
			System.out.println(new String(msg.getBytes(encoding), encoding));
		}
		in.close();
	}
    public static String getEncoding(String str) {
		String encode = "GB2312";
		try {
			if (str.equals(new String(str.getBytes(encode), encode))) { // 判断是不是GB2312
				String s = encode;
				return s; // 是的话,返回“GB2312“,以下代码同理
			}
			encode = "ISO-8859-1";
			if (str.equals(new String(str.getBytes(encode), encode))) { // 判断是不是ISO-8859-1
				String s1 = encode;
				return s1;
			}
			encode = "UTF-8";
			if (str.equals(new String(str.getBytes(encode), encode))) { // 判断是不是UTF-8
				String s2 = encode;
				return s2;
			}
			encode = "GBK";
			if (str.equals(new String(str.getBytes(encode), encode))) { // 判断是不是GBK
				String s3 = encode;
				return s3;
			}

		} catch (Exception exception3) {

		}
		return "";
	}// 如果都不是,说明输入的内容不属于常见的编码
}

                                        

                                                                    JAVA程序猿成长之路

                                                  分享学习资源,学习方法,记录程序员生活。

猜你喜欢

转载自blog.csdn.net/niugang0920/article/details/82228172
jav