SSH

原创
2017/09/12 09:37
阅读数 172

远程执行Linux命令,依赖ganymed-ssh2.jar

public class SSHUtil {
	
	private static final Logger logger = LoggerFactory.getLogger(SSHUtil.class);
	
	public static String execCommand(String host, int port, String username, String password, String command) {
		String result = "";
		Connection conn = null;
		Session ssh = null;
		try {
			//conn
			conn = new Connection(host, port);
			conn.connect();
			logger.info("Connecting to "+host+":"+port+"...");
			boolean authenticated = conn.authenticateWithPassword(username, password);
			if(!authenticated) {
				logger.info("Username or password is wrong");
			} else {
				logger.info("Connected");
				//open session
				ssh = conn.openSession();
				//exec command
				logger.info("Command start");
				logger.info("Command " + command);
				ssh.execCommand(command);
				InputStream  is = new StreamGobbler(ssh.getStdout());
				BufferedReader br = new BufferedReader(new InputStreamReader(is));
				while(true){
					String line = br.readLine();
					if(line==null){
						break;
					}
					result+= new String(line.getBytes("GBK"),"UTF-8")+"\r\n";
				}
				logger.info("Command end");
				br.close();
			}
		} catch (ConnectException e) {
			e.printStackTrace();
			logger.error("Connection refused", e);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("Exec command error", e);
		} finally {
			if(ssh!=null) {
				ssh.close();
			}
			if(conn!=null) {
				conn.close();
			}
		}
		return result;
	}
	
	public static void main(String[] args) {
		String host = "192.168.3.9";
		int port = 22;
		String username = "root";
		String password = "redhat";
		String command = "uname -s -r -v";
		String result = execCommand(host, port, username, password, command);
		System.out.println("result="+result);
	}

}
---------------------------------------------------------------------------------------------------------

远程执行Linux命令,依赖jsch.jar(JSch=Java Secure Channel)

public class SSHJSchUtil {
	
	private static final Logger logger = LoggerFactory.getLogger(SSHJSchUtil.class);
	
	public static String execCommand(String host, int port, String username,String password, String command) {
		String result = "";
		Session session = null;
		ChannelExec openChannel =null;
		try {
			//Session
			logger.debug("Connecting to "+host+":"+port+"...");
			JSch jsch=new JSch();
			session = jsch.getSession(username, host, port);
			session.setPassword(password);
			session.setTimeout(2000);
			Properties config = new Properties ();
			config.put("StrictHostKeyChecking", "no");
			session.setConfig(config);
			session.connect();
			logger.debug("Connected");
			//Channel
			logger.debug("Command start");
			logger.debug("Command " + command);
			openChannel = (ChannelExec) session.openChannel("exec");
			openChannel.setCommand(command);
			//int exitStatus = openChannel.getExitStatus();
			openChannel.connect();
			InputStream in = openChannel.getInputStream(); 
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			while(true){
				String line = br.readLine();
				if(line==null){
					break;
				}
				result+= new String(line.getBytes("GBK"),"UTF-8")+"\r\n";
			}
			br.close();
			logger.debug("Command end");
		} catch (JSchException e) {
			e.printStackTrace();
			logger.error("Connection refused", e);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("Exec command error", e);
		} finally {
			if(openChannel!=null&&!openChannel.isClosed()){
				openChannel.disconnect();
			}
			if(session!=null&&session.isConnected()){
				session.disconnect();
			}
		}
		return result;
	}
	
	public static void main(String[] args) {
		String host = "192.168.3.9";
		int port = 22;
		String username = "root";
		String password = "redhat";
		String command = "uname -s -r -v";
		String result = execCommand(host, port, username, password, command);
		System.out.println("result="+result);
	}

}

 

 

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
1
分享
返回顶部
顶部