java通過ssh命令獲取linux服務器狀態信息


1、使用jar包:jsch-0.1.24.jar

2、代碼示例

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

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

/**
 * SSH工具類
 */
public class SSHTest {

	/**
	 * 遠程 執行命令並返回結果調用過程 是同步的(執行完才會返回)
	 * 
	 * @param host
	 *            主機名
	 * @param user
	 *            用戶名
	 * @param psw
	 *            密碼
	 * @param port
	 *            端口
	 * @param command
	 *            命令
	 * @return
	 */
	public static String exec(String host, String user, String psw, int port, String command) {
		String result = "";
		Session session = null;
		ChannelExec openChannel = null;
		try {
			// String osName = System.getProperty("os.name");
			// System.out.println("os name:"+osName);
			JSch jsch = new JSch();
			session = jsch.getSession(user, host, port);
			java.util.Properties config = new java.util.Properties();
			config.put("StrictHostKeyChecking", "no");
			session.setConfig(config);
			session.setPassword(psw);
			session.connect();
			openChannel = (ChannelExec) session.openChannel("exec");
			openChannel.setCommand(command);
			int exitStatus = openChannel.getExitStatus();
			// System.out.println(exitStatus);
			openChannel.connect();
			InputStream in = openChannel.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(in));
			String buf = null;
			while ((buf = reader.readLine()) != null) {
				result += new String(buf.getBytes("gbk"), "UTF-8") + "  \r\n";
			}
		} catch (JSchException | IOException e) {
			result += e.getMessage();
		} finally {
			if (openChannel != null && !openChannel.isClosed()) {
				openChannel.disconnect();
			}
			if (session != null && session.isConnected()) {
				session.disconnect();
			}
		}
		return result;
	}

	public static void main(String args[]) {
		String memory = exec("192.168.0.135", "name", "pwd", 22, "free\n df -h\n top -b -n 1\n");// 內存
																									// (命令\n分割,合起來寫也ok)
		// String disk = exec("192.168.0.135", "name", "pwd", 22, "df -h\n");//
		// 磁盤
		// cpu
		// String cpu = exec("192.168.0.135", "name", "pwd", 22, "top -b -n
		// 1\n");// 直接寫top輸出為空,動態命令,只能加參數輸出一次

		System.out.println(memory);
		// System.out.println(disk);
		// System.out.println(cpu);
	}
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM