2 * Copyright (c) 2015 Huawei, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.nemo.tool.sandbox;
11 import ch.ethz.ssh2.Connection;
12 import ch.ethz.ssh2.Session;
13 import ch.ethz.ssh2.StreamGobbler;
14 import org.opendaylight.nemo.tool.sandbox.utils.Config;
16 import java.io.BufferedReader;
17 import java.io.IOException;
18 import java.io.InputStream;
19 import java.io.InputStreamReader;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
24 * Created by hj on 12/9/15.
26 public class CmdExecutor {
27 private static Logger log = LoggerFactory.getLogger(CmdExecutor.class);
28 private static Connection sshConnection;
29 private static String strHostName = Config.getHostName();
30 private static String strUserName = Config.getHostUser();
31 private static String strPassword = Config.getHostPassword();
33 public static boolean open() {
35 sshConnection = new Connection(strHostName);
36 sshConnection.connect();
37 if (false == sshConnection.authenticateWithPassword(strUserName, strPassword)) {
38 throw new IOException("Authentication failed!");
42 } catch (IOException objException) {
43 log.error("Exceptions:",objException);
44 if (null != sshConnection) {
45 sshConnection.close();
52 public static void close() {
53 if (null != sshConnection) {
54 sshConnection.close();
59 public static String sshExecute(String command) {
60 Session session = null;
62 session = sshConnection.openSession();
63 if (!"root".equals(Config.getHostName())) {
64 command = "sudo " + command;
66 session.execCommand(command);
67 InputStream stdout = new StreamGobbler(session.getStdout());
68 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stdout));
71 String line = bufferedReader.readLine();
73 result += "\r\n" + line;
80 } catch (IOException objException) {
81 log.error("Exceptions:",objException);
83 if (null != session) {
90 public static String queryInterfaceMac(String name) {
91 String result = sshExecute("ifconfig " + name);
92 return getMacFromResult(result);
95 public static String queryInterfaceMac(String name, String namespce) {
96 String result = sshExecute("ip netns exec " + namespce + " ifconfig " + name);
97 return getMacFromResult(result);
100 private static String getMacFromResult(String result) {
101 String args[] = result.split("\r\n");
102 for (int i = 0; i < args.length; i++) {
103 String arg = args[i].trim();
104 if (arg.contains("HWaddr")) {
105 String s[] = arg.split(" ");
106 return s[s.length - 1];