Added MultiCommandExecutor class and an incomplete proof of concept ip scanner

This commit is contained in:
Ziver Koc 2016-09-11 21:55:54 +02:00
parent 46de7e05d1
commit 985cb8b1de
10 changed files with 353 additions and 45 deletions

View file

@ -0,0 +1,80 @@
package zutil.net;
import zutil.osal.MultiCommandExecutor;
import zutil.osal.OSAbstractionLayer;
import java.io.*;
/**
* Created by Ziver on 2016-09-11.
*/
public class InetScanner {
private static final int TIMEOUT_MS = 50;
public static void main(String[] args){
//scan();
scan2();
}
public static void scan(){
for (int i = 1; i < 255; i++) {
String ip = "192.168.1."+i;
System.out.println(ip+": "+isReachableByPing(ip));
}
}
public static boolean isReachableByPing(String host) {
try{
String[] output = OSAbstractionLayer.exec(getPlatformPingCmd(host));
if (output[2].contains("TTL=") || output[2].contains("ttl="))
return true;
} catch( Exception e ) {
e.printStackTrace();
}
return false;
}
public static void scan2(){
try{
MultiCommandExecutor exec = new MultiCommandExecutor();
// execute the desired command (here: ls) n times
for (int i = 1; i < 255; i++) {
try {
String ip = "192.168.1."+i;
exec.exec(getPlatformPingCmd(ip));
System.out.print(ip+": ");
boolean online = false;
for (String line; (line=exec.readLine()) != null;) {
if (line.contains("TTL=") || line.contains("ttl="))
online = true;
}
System.out.println(online);
}
catch (IOException e) {
System.out.println(e);
}
}
exec.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
private static String getPlatformPingCmd(String ip){
switch (OSAbstractionLayer.getInstance().getOSType()){
case Windows:
return "ping -n 1 -w "+ TIMEOUT_MS +" " + ip;
case Linux:
case MacOS:
return "ping -c 1 -W "+ TIMEOUT_MS +" " + ip;
default:
return null;
}
}
}

View file

@ -0,0 +1,105 @@
package zutil.osal;
import zutil.parser.Base64Encoder;
import java.io.*;
import java.security.SecureRandom;
import java.security.Security;
/**
* This class starts a platform specific shell and runs all commands
* in a single process thereby lowering the execution time.
*
* <br><br>
*/
public class MultiCommandExecutor implements AutoCloseable{
private static final String SHELL_WINDOWS = "cmd.exe";
private static final String SHELL_LINUX = "/bin/bash";
private String delimiter;
private Process process;
private BufferedWriter stdin;
private BufferedReader stdout;
private boolean eol = true;
public MultiCommandExecutor(){
try {
// Generate delimiter
byte[] tmp = new byte[16];
SecureRandom.getInstance("SHA1PRNG").nextBytes(tmp);
delimiter = Base64Encoder.encode(tmp);
//init shell
String shellCmd;
switch (OSAbstractionLayer.getInstance().getOSType()){
case Windows:
shellCmd = SHELL_WINDOWS; break;
case Linux:
case MacOS:
shellCmd = SHELL_LINUX; break;
default:
throw new RuntimeException("Unsupported OS");
}
process = new ProcessBuilder(shellCmd).start();
//get stdin of shell
stdin = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
stdout = new BufferedReader(new InputStreamReader(process.getInputStream()));
} catch (RuntimeException e){
throw e;
} catch (Exception e){
throw new RuntimeException("Unable to initiate shell",e);
}
}
public void exec(String cmd) throws IOException {
while (readLine() != null); // read the output from previous exec
eol = false;
stdin.write(cmd);
switch (OSAbstractionLayer.getInstance().getOSType()){
case Windows:
stdin.write(" & echo & echo " + delimiter); break;
case Linux:
case MacOS:
stdin.write(" ; echo ; echo " + delimiter); break;
}
stdin.newLine();
stdin.flush();
}
/**
* @return one line from command execution, or null if the command has finished running
*/
public String readLine() throws IOException {
if (eol)
return null;
String line = stdout.readLine();
if (line != null && line.startsWith(delimiter)) {
eol = true;
return null;
}
return line;
}
@Override
public void close(){
try {
// finally close the shell by execution exit command
stdin.write("exit");
stdin.newLine();
stdin.flush();
process.destroy();
process = null;
stdin = null;
stdout = null;
} catch (Exception e){
e.printStackTrace();
}
}
}

View file

@ -34,8 +34,8 @@ import java.util.ArrayList;
* User: Ziver * User: Ziver
*/ */
public abstract class OSAbstractionLayer { public abstract class OSAbstractionLayer {
public static enum OSType{ public enum OSType{
Windows, Linux, MacOS, Unix Windows, Linux, MacOS, Unix, Unknown
} }
// Variables // Variables
@ -51,7 +51,8 @@ public abstract class OSAbstractionLayer {
String os = System.getProperty("os.name"); String os = System.getProperty("os.name");
if (os.contains("Linux")) return new OsalLinuxImpl(); if (os.contains("Linux")) return new OsalLinuxImpl();
else if(os.contains("Windows")) return new OsalWindowsImpl(); else if(os.contains("Windows")) return new OsalWindowsImpl();
else return null; else if(os.contains("Mac")) return new OsalMacOSImpl();
else return new OsalDummyImpl();
} }
/** /**
@ -60,8 +61,8 @@ public abstract class OSAbstractionLayer {
* @param cmd the command to run * @param cmd the command to run
* @return first line of the command * @return first line of the command
*/ */
protected static String getFirstLineFromCommand(String cmd) { protected static String getFirstLineFromExec(String cmd) {
String[] tmp = runCommand(cmd); String[] tmp = exec(cmd);
if(tmp.length > 1) if(tmp.length > 1)
return tmp[0]; return tmp[0];
return null; return null;
@ -73,23 +74,19 @@ public abstract class OSAbstractionLayer {
* @param cmd the command to run * @param cmd the command to run
* @return a String list of the output of the command * @return a String list of the output of the command
*/ */
public static String[] runCommand(String cmd) { public static String[] exec(String cmd) {
ArrayList<String> ret = new ArrayList<String>(); ArrayList<String> ret = new ArrayList<String>();
try { try {
Runtime runtime = Runtime.getRuntime(); Process proc = Runtime.getRuntime().exec(cmd);
Process proc = runtime.exec(cmd);
proc.waitFor(); proc.waitFor();
BufferedReader output = new BufferedReader(new InputStreamReader(proc.getInputStream())); BufferedReader output = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line; String line;
while ((line = output.readLine()) != null) { while ((line = output.readLine()) != null) {
ret.add(line); ret.add(line);
} }
output.close(); output.close();
} catch (InterruptedException e) { } catch (Exception e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -101,11 +98,6 @@ public abstract class OSAbstractionLayer {
*/ */
public abstract OSType getOSType(); public abstract OSType getOSType();
/**
* @return a more specific OS or distribution name e.g "ubuntu", "suse", "windows"
*/
public abstract String getOSName();
/** /**
* @return the OS version e.g windows: "vista", "7"; ubuntu: "10.4", "12.10" * @return the OS version e.g windows: "vista", "7"; ubuntu: "10.4", "12.10"
*/ */

View file

@ -0,0 +1,68 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.osal;
import java.io.File;
/**
* This is a dummy implementation for unknown platforms
*/
public class OsalDummyImpl extends OSAbstractionLayer {
@Override
public OSType getOSType() {
return OSType.Unknown;
}
@Override
public String getOSVersion() {
throw new UnsupportedOperationException();
}
@Override
public String getKernelVersion() {
throw new UnsupportedOperationException();
}
@Override
public String getUsername() {
throw new UnsupportedOperationException();
}
@Override
public File getUserConfigPath() {
throw new UnsupportedOperationException();
}
@Override
public File getGlobalConfigPath() {
throw new UnsupportedOperationException();
}
@Override
public HardwareAbstractionLayer getHAL() {
throw new UnsupportedOperationException();
}
}

View file

@ -27,7 +27,7 @@ package zutil.osal;
import java.io.File; import java.io.File;
/** /**
* User: Ziver * Linux platform specific implementation
*/ */
public class OsalLinuxImpl extends OSAbstractionLayer { public class OsalLinuxImpl extends OSAbstractionLayer {
private static HalLinuxImpl hal; private static HalLinuxImpl hal;
@ -37,20 +37,16 @@ public class OsalLinuxImpl extends OSAbstractionLayer {
return OSType.Linux; return OSType.Linux;
} }
@Override
public String getOSName() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override @Override
public String getOSVersion() { public String getOSVersion() {
return null; //To change body of implemented methods use File | Settings | File Templates. throw new UnsupportedOperationException();
} }
@Override @Override
public String getKernelVersion() { public String getKernelVersion() {
try{ try{
return super.getFirstLineFromCommand("uname -r"); return super.getFirstLineFromExec("uname -r");
} catch(Exception e){ } catch(Exception e){
e.printStackTrace(); e.printStackTrace();
} }
@ -60,7 +56,7 @@ public class OsalLinuxImpl extends OSAbstractionLayer {
@Override @Override
public String getUsername() { public String getUsername() {
try{ try{
return super.getFirstLineFromCommand("whoami"); return super.getFirstLineFromExec("whoami");
} catch(Exception e){ } catch(Exception e){
e.printStackTrace(); e.printStackTrace();
} }

View file

@ -0,0 +1,71 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.osal;
import com.mysql.jdbc.NotImplemented;
import java.io.File;
/**
* MacOS platform specific implementation
*/
public class OsalMacOSImpl extends OSAbstractionLayer {
@Override
public OSType getOSType() {
return OSType.MacOS;
}
@Override
public String getOSVersion() {
throw new UnsupportedOperationException();
}
@Override
public String getKernelVersion() {
throw new UnsupportedOperationException();
}
@Override
public String getUsername() {
throw new UnsupportedOperationException();
}
@Override
public File getUserConfigPath() {
return new File("/home/"+getUsername());
}
@Override
public File getGlobalConfigPath() {
throw new UnsupportedOperationException();
}
@Override
public HardwareAbstractionLayer getHAL() {
throw new UnsupportedOperationException();
}
}

View file

@ -27,28 +27,24 @@ package zutil.osal;
import java.io.File; import java.io.File;
/** /**
* User: ezivkoc * Windows platform specific implementation
*/ */
public class OsalWindowsImpl extends OSAbstractionLayer { public class OsalWindowsImpl extends OSAbstractionLayer {
@Override
public OSType getOSType() {
return null;
}
@Override @Override
public String getOSName() { public OSType getOSType() {
return null; return OSType.Windows;
} }
@Override @Override
public String getOSVersion() { public String getOSVersion() {
return null; throw new UnsupportedOperationException();
} }
@Override @Override
public String getKernelVersion() { public String getKernelVersion() {
try { try {
return getFirstLineFromCommand("ver"); return getFirstLineFromExec("ver");
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -57,21 +53,21 @@ public class OsalWindowsImpl extends OSAbstractionLayer {
@Override @Override
public String getUsername() { public String getUsername() {
return null; throw new UnsupportedOperationException();
} }
@Override @Override
public File getUserConfigPath() { public File getUserConfigPath() {
return null; throw new UnsupportedOperationException();
} }
@Override @Override
public File getGlobalConfigPath() { public File getGlobalConfigPath() {
return null; throw new UnsupportedOperationException();
} }
@Override @Override
public HardwareAbstractionLayer getHAL() { public HardwareAbstractionLayer getHAL() {
return null; throw new UnsupportedOperationException();
} }
} }

View file

@ -43,13 +43,13 @@ public class AptGet {
public static void install(String pkg) { public static void install(String pkg) {
update(); update();
OSAbstractionLayer.runCommand("apt-get -y install " + pkg); OSAbstractionLayer.exec("apt-get -y install " + pkg);
packageTimer.reset(); packageTimer.reset();
} }
public static void upgrade(){ public static void upgrade(){
update(); update();
OSAbstractionLayer.runCommand("apt-get -y " + OSAbstractionLayer.exec("apt-get -y " +
// Dont display configuration conflicts // Dont display configuration conflicts
"-o Dpkg::Options::=\"--force-confdef\" -o Dpkg::Options::=\"--force-confold\" " + "-o Dpkg::Options::=\"--force-confdef\" -o Dpkg::Options::=\"--force-confold\" " +
"upgrade"); "upgrade");
@ -59,13 +59,13 @@ public class AptGet {
public static void update(){ public static void update(){
// Only run every 5 min // Only run every 5 min
if(updateTimer.hasTimedOut()){ if(updateTimer.hasTimedOut()){
OSAbstractionLayer.runCommand("apt-get update"); OSAbstractionLayer.exec("apt-get update");
updateTimer.start(); updateTimer.start();
} }
} }
public static void purge(String pkg) { public static void purge(String pkg) {
OSAbstractionLayer.runCommand("apt-get --purge remove " + pkg); OSAbstractionLayer.exec("apt-get --purge remove " + pkg);
packageTimer.reset(); packageTimer.reset();
} }
@ -77,7 +77,7 @@ public class AptGet {
public static synchronized void updatePackages(){ public static synchronized void updatePackages(){
// Only run every 5 min // Only run every 5 min
if(packageTimer.hasTimedOut()){ if(packageTimer.hasTimedOut()){
String[] output = OSAbstractionLayer.runCommand("dpkg --list"); String[] output = OSAbstractionLayer.exec("dpkg --list");
for(int i=5; i<output.length; ++i) { for(int i=5; i<output.length; ++i) {
packages.put(output[i], new Package(output[5])); packages.put(output[i], new Package(output[5]));
} }

View file

@ -33,7 +33,7 @@ public class Ps {
private static OSAbstractionLayer os = OSAbstractionLayer.getInstance(); private static OSAbstractionLayer os = OSAbstractionLayer.getInstance();
public static boolean isRunning(int pid){ public static boolean isRunning(int pid){
String[] output = os.runCommand("ps -p "+pid); String[] output = os.exec("ps -p "+pid);
return output.length > 1; return output.length > 1;
} }
} }

View file

@ -67,7 +67,7 @@ public class TypePerf {
private static DataNode[] execute(String path) throws IOException { private static DataNode[] execute(String path) throws IOException {
DataNode[] ret = new DataNode[2]; DataNode[] ret = new DataNode[2];
String[] output = OSAbstractionLayer.runCommand("typeperf \""+ path +"\" -SC 0 -y"); String[] output = OSAbstractionLayer.exec("typeperf \""+ path +"\" -SC 0 -y");
CSVParser parser = new CSVParser(new StringReader(output[1] + "\n" + output[2])); CSVParser parser = new CSVParser(new StringReader(output[1] + "\n" + output[2]));
ret[0] = parser.getHeaders(); ret[0] = parser.getHeaders();