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;
22 * Created by hj on 12/9/15.
24 public class CmdExecutor {
25 private static Connection sshConnection;
26 private static String strHostName = Config.getHostName();
27 private static String strUserName = Config.getHostUser();
28 private static String strPassword = Config.getHostPassword();
30 public static boolean open() {
32 sshConnection = new Connection(strHostName);
33 sshConnection.connect();
34 if (false == sshConnection.authenticateWithPassword(strUserName, strPassword)) {
35 throw new IOException("Authentication failed!");
39 } catch (IOException objException) {
40 objException.printStackTrace();
41 if (null != sshConnection) {
42 sshConnection.close();
49 public static void close() {
50 if (null != sshConnection) {
51 sshConnection.close();
56 public static String sshExecute(String command) {
57 Session session = null;
59 session = sshConnection.openSession();
60 if (!"root".equals(Config.getHostName())) {
61 command = "sudo " + command;
63 session.execCommand(command);
64 InputStream stdout = new StreamGobbler(session.getStdout());
65 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stdout));
68 String line = bufferedReader.readLine();
70 result += "\r\n" + line;
77 } catch (IOException objException) {
78 objException.printStackTrace();
80 if (null != session) {
87 public static String queryInterfaceMac(String name) {
88 String result = sshExecute("ifconfig " + name);
89 return getMacFromResult(result);
92 public static String queryInterfaceMac(String name, String namespce) {
93 String result = sshExecute("ip netns exec " + namespce + " ifconfig " + name);
94 return getMacFromResult(result);
97 private static String getMacFromResult(String result) {
98 String args[] = result.split("\r\n");
99 for (int i = 0; i < args.length; i++) {
100 String arg = args[i].trim();
101 if (arg.contains("HWaddr")) {
102 String s[] = arg.split(" ");
103 return s[s.length - 1];