O objetivo deste código de programa é monitorar conexões que são feitas na máquina. O Netstat permite exibir as conexões e as portas utilizadas no computador exibindo o computador remoto que está conectado assim como a sua porta utilizada. O objetivo principal aqui é a segurança e monitoramento da maquina. Conforme a opção do Netsat também é possível verificar qual é o programa que está sendo utilizado naquela conexão, mas essa informação em nem todos os casos é exibida. No programa, o comando roda a cada 5 minutos (300 segundos). Caso exista algum programa indevido é necessário fazer o reconhecimento e o bloqueio através do firewall. Na classe CommandLine é executado o comando, onde o Java chama o comando em CMD.EXE do sistema operacional. Na classe MyRun3 criamos o arquivo no local determinado nomeado com a data e a hora da execução. Na classe Begginer temos a programação da chamada a cada 5 minutos e da chamada principal do inicio do programa. Os pacotes devem sex exportados pelo Eclipse através da opção JAR Executável e na combobox deve ser selecionada a classe da chamada principal que contém o método Main no nosso caso a classe Begginer.
package Cap2;
import java.io.*;
public class CommandLine {
// Needed to run commands in the command line
private Runtime runtime;
private Process process;
// Output of the executed command
private String stdinData;
private String stderrData;
// Constructor
public CommandLine() {
runtime = Runtime.getRuntime();
process = null;
stdinData = "";
stderrData = "";
}
// Return executed command output data
public String getStdinData() {
return stdinData;
}
public String getStderrData() {
return stderrData;
}
// Execute a single command with all its arguments
public void execute(String command) {
try {
process = runtime.exec(command);
} catch (Exception ex) {
System.err.println(ex);
}
pullProcessData();
}
// Execute a single command in cmdArray,
// define environment settings in envp and
// set working directory to dir
public void execute(String[] cmdArray, String[] envp, File dir) {
try {
process = runtime.exec(cmdArray, envp, dir);
} catch (Exception ex) {
System.err.println(ex);
}
pullProcessData();
}
// Obtain all data sent by the process to stdout and stderr
private void pullProcessData() {
try {
StringBuffer stdinBuffer = new StringBuffer();
StringBuffer stderrBuffer = new StringBuffer();
InputStream stdinStream = process.getInputStream();
InputStream stderrStream = process.getErrorStream();
new InputStreamHandler(stdinBuffer, stdinStream);
new InputStreamHandler(stderrBuffer, stderrStream);
process.waitFor();
stdinData = stdinBuffer.toString();
stderrData = stderrBuffer.toString();
} catch (Exception ex) {
System.err.println(ex);
}
}
// Private inner class used to handle input streams
private class InputStreamHandler extends Thread {
private InputStream m_stream;
private StringBuffer m_captureBuffer;
InputStreamHandler(StringBuffer captureBuffer, InputStream stream) {
m_stream = stream;
m_captureBuffer = captureBuffer;
start();
}
public void run() {
try {
int nextChar;
while ((nextChar = m_stream.read()) != -1)
m_captureBuffer.append((char) nextChar);
} catch (IOException ioex) {
System.err.println(ioex);
}
}
}
}
package Cap2;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.GregorianCalendar;
public class MyRun3 {
public void executeCommand ( ) {
// TODO Auto-generated method stub
String nomearquivo;
StringBuilder sb = new StringBuilder();
// cria um GregorianCalendar que vai conter a hora atual
GregorianCalendar d = new GregorianCalendar();
// anexa do StringBuilder os dados da hora
sb.append( d.get( GregorianCalendar.YEAR) );
sb.append( "_" );
sb.append( d.get( GregorianCalendar.MONTH ) );
sb.append( "_" );
sb.append( d.get( GregorianCalendar.DAY_OF_MONTH ) );
sb.append( "_" );
sb.append( d.get( GregorianCalendar.HOUR_OF_DAY ) );
sb.append( "h" );
sb.append( d.get( GregorianCalendar.MINUTE ) );
sb.append( "m" );
sb.append( d.get( GregorianCalendar.SECOND ) );
sb.append( "s" );
// retorna a String do StringBuilder
nomearquivo="d:\\filters\\logNetstat_";
nomearquivo+=sb.toString();
nomearquivo+=".txt";
CommandLine cl = new CommandLine();
cl.execute( "cmd /c netstat -an" );
System.out.print( cl.getStdinData() );
System.out.print( cl.getStderrData() );
OutputStream os = null;
try {
os = new FileOutputStream(nomearquivo);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
try {
bw.write(cl.getStdinData() );
bw.write(cl.getStderrData() );
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package Cap2;
public class Begginer {
public static void main(String[] args) {
// TODO Auto-generated method stub
MyRun3 myrun3 = new MyRun3();
while (true) {
myrun3.executeCommand();
for (int i = 0; i < 300 ; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
package Cap2;
import java.io.*;
public class CommandLine {
// Needed to run commands in the command line
private Runtime runtime;
private Process process;
// Output of the executed command
private String stdinData;
private String stderrData;
// Constructor
public CommandLine() {
runtime = Runtime.getRuntime();
process = null;
stdinData = "";
stderrData = "";
}
// Return executed command output data
public String getStdinData() {
return stdinData;
}
public String getStderrData() {
return stderrData;
}
// Execute a single command with all its arguments
public void execute(String command) {
try {
process = runtime.exec(command);
} catch (Exception ex) {
System.err.println(ex);
}
pullProcessData();
}
// Execute a single command in cmdArray,
// define environment settings in envp and
// set working directory to dir
public void execute(String[] cmdArray, String[] envp, File dir) {
try {
process = runtime.exec(cmdArray, envp, dir);
} catch (Exception ex) {
System.err.println(ex);
}
pullProcessData();
}
// Obtain all data sent by the process to stdout and stderr
private void pullProcessData() {
try {
StringBuffer stdinBuffer = new StringBuffer();
StringBuffer stderrBuffer = new StringBuffer();
InputStream stdinStream = process.getInputStream();
InputStream stderrStream = process.getErrorStream();
new InputStreamHandler(stdinBuffer, stdinStream);
new InputStreamHandler(stderrBuffer, stderrStream);
process.waitFor();
stdinData = stdinBuffer.toString();
stderrData = stderrBuffer.toString();
} catch (Exception ex) {
System.err.println(ex);
}
}
// Private inner class used to handle input streams
private class InputStreamHandler extends Thread {
private InputStream m_stream;
private StringBuffer m_captureBuffer;
InputStreamHandler(StringBuffer captureBuffer, InputStream stream) {
m_stream = stream;
m_captureBuffer = captureBuffer;
start();
}
public void run() {
try {
int nextChar;
while ((nextChar = m_stream.read()) != -1)
m_captureBuffer.append((char) nextChar);
} catch (IOException ioex) {
System.err.println(ioex);
}
}
}
}
package Cap2;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.GregorianCalendar;
public class MyRun3 {
public void executeCommand ( ) {
// TODO Auto-generated method stub
String nomearquivo;
StringBuilder sb = new StringBuilder();
// cria um GregorianCalendar que vai conter a hora atual
GregorianCalendar d = new GregorianCalendar();
// anexa do StringBuilder os dados da hora
sb.append( d.get( GregorianCalendar.YEAR) );
sb.append( "_" );
sb.append( d.get( GregorianCalendar.MONTH ) );
sb.append( "_" );
sb.append( d.get( GregorianCalendar.DAY_OF_MONTH ) );
sb.append( "_" );
sb.append( d.get( GregorianCalendar.HOUR_OF_DAY ) );
sb.append( "h" );
sb.append( d.get( GregorianCalendar.MINUTE ) );
sb.append( "m" );
sb.append( d.get( GregorianCalendar.SECOND ) );
sb.append( "s" );
// retorna a String do StringBuilder
nomearquivo="d:\\filters\\logNetstat_";
nomearquivo+=sb.toString();
nomearquivo+=".txt";
CommandLine cl = new CommandLine();
cl.execute( "cmd /c netstat -an" );
System.out.print( cl.getStdinData() );
System.out.print( cl.getStderrData() );
OutputStream os = null;
try {
os = new FileOutputStream(nomearquivo);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
try {
bw.write(cl.getStdinData() );
bw.write(cl.getStderrData() );
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package Cap2;
public class Begginer {
public static void main(String[] args) {
// TODO Auto-generated method stub
MyRun3 myrun3 = new MyRun3();
while (true) {
myrun3.executeCommand();
for (int i = 0; i < 300 ; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
Nenhum comentário:
Postar um comentário