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 Logger log = LoggerFactory.getLogger(CmdExecutor.class);
26 private static Connection sshConnection;
27 private static String strHostName = Config.getHostName();
28 private static String strUserName = Config.getHostUser();
29 private static String strPassword = Config.getHostPassword();
31 public static boolean open() {
33 sshConnection = new Connection(strHostName);
34 sshConnection.connect();
35 if (false == sshConnection.authenticateWithPassword(strUserName, strPassword)) {
36 throw new IOException("Authentication failed!");
40 } catch (IOException objException) {
41 // objException.printStackTrace();
42 log.error(objException);
43 if (null != sshConnection) {
44 sshConnection.close();
51 public static void close() {
52 if (null != sshConnection) {
53 sshConnection.close();
58 public static String sshExecute(String command) {
59 Session session = null;
61 session = sshConnection.openSession();
62 if (!"root".equals(Config.getHostName())) {
63 command = "sudo " + command;
65 session.execCommand(command);
66 InputStream stdout = new StreamGobbler(session.getStdout());
67 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stdout));
70 String line = bufferedReader.readLine();
72 result += "\r\n" + line;
79 } catch (IOException objException) {
80 // objException.printStackTrace();
81 log.error(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];