();
18 | commands.add("ping");
19 | commands.add(ip);
20 | String s = null;
21 | ProcessBuilder pb = new ProcessBuilder(commands);
22 | Process process = null;
23 | try {
24 | process = pb.start();
25 | } catch (IOException ex) {
26 | log.error(ex);
27 | }
28 | BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
29 | BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
30 | try {
31 | while ((s = stdInput.readLine()) != null) {
32 |
33 | String newString = new String(s.getBytes("windows-1251"), "cp866");//change encoding
34 | stream.println(newString);
35 | }
36 | } catch (IOException ex) {
37 | log.error(ex);
38 | }
39 | // read any errors from the attempted command
40 | try {
41 | while ((s = stdError.readLine()) != null) {
42 | stream.println(s);
43 | }
44 | } catch (IOException ex) {
45 | log.error(ex);
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/main/java/com/github/dmtk/Port.java:
--------------------------------------------------------------------------------
1 | package com.github.dmtk;
2 | import org.apache.log4j.Logger;
3 |
4 | public class Port{
5 |
6 | private int port;
7 | private final int defaultPort = 2;
8 | private final static Logger log = Logger.getLogger(Port.class);
9 |
10 | public Port(String port) {
11 |
12 | try {
13 | intialize(Integer.parseInt(port));
14 | } catch (NumberFormatException ex) {
15 | log.error("Wrong port number format" + port);
16 | }
17 |
18 | }
19 |
20 | public int getNum(){
21 | return port;
22 | }
23 |
24 | public Port(int port) {
25 | intialize(port);
26 | }
27 |
28 | private void intialize(int port) {
29 | if (validate(port)) {
30 | this.port = port;
31 | } else {
32 | this.port = defaultPort;
33 | log.error("Wrong port number" + port);
34 | }
35 | }
36 |
37 | private boolean validate(int vlan) {
38 | return vlan > 0 && vlan < 52;//Ports range
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/com/github/dmtk/Ssh.java:
--------------------------------------------------------------------------------
1 | package com.github.dmtk;
2 |
3 | import com.jcraft.jsch.*;
4 | import java.io.ByteArrayInputStream;
5 | import java.io.IOException;
6 | import java.io.PrintStream;
7 | import javax.swing.*;
8 | import org.apache.log4j.Logger;
9 |
10 | public class Ssh extends Terminal {
11 |
12 | private Session session;
13 | private final static Logger log = Logger.getLogger(Ssh.class);
14 |
15 | public void start(String host, int port, PrintStream output, String user, String password) {
16 |
17 | try {
18 | JSch jsch = new JSch();
19 | //jsch.setKnownHosts("/home/foo/.ssh/known_hosts");
20 | session = jsch.getSession(user, host, port);
21 | session.setPassword(password);
22 | UserInfo ui = new MyUserInfo() {
23 | public void showMessage(String message) {
24 | JOptionPane.showMessageDialog(null, message);
25 | }
26 |
27 | public boolean promptYesNo(String message) {
28 | Object[] options = {"yes", "no"};
29 | int foo = JOptionPane.showOptionDialog(null,
30 | message,
31 | "Warning",
32 | JOptionPane.DEFAULT_OPTION,
33 | JOptionPane.WARNING_MESSAGE,
34 | null, options, options[0]);
35 | return foo == 0;
36 | }
37 |
38 | // If password is not given before the invocation of Session#connect(),
39 | // implement also following methods,
40 | // * UserInfo#getPassword(),
41 | // * UserInfo#promptPassword(String message) and
42 | // * UIKeyboardInteractive#promptKeyboardInteractive()
43 | };
44 | session.setUserInfo(ui);
45 | // It must not be recommended, but if you want to skip host-key check,
46 | // invoke following,
47 | // session.setConfig("StrictHostKeyChecking", "no");
48 | //session.connect();
49 | session.connect(30000); // making a connection with timeout.
50 | Channel channel = session.openChannel("shell");
51 | channel.setInputStream(System.in);
52 | channel.setOutputStream(output);
53 | streamOut = channel.getOutputStream();
54 |
55 | // Enable agent-forwarding.
56 | //((ChannelShell)channel).setAgentForwarding(true);
57 |
58 | /*
59 | // a hack for MS-DOS prompt on Windows.
60 | channel.setInputStream(new FilterInputStream(System.in){
61 | public int read(byte[] b, int off, int len)throws IOException{
62 | return in.read(b, off, (len>1024?1024:len));
63 | }
64 | });
65 | */
66 | /*
67 | // Choose the pty-type "vt102".
68 | ((ChannelShell)channel).setPtyType("vt102");
69 | */
70 | /*
71 | // Set environment variable "LANG" as "ja_JP.eucJP".
72 | ((ChannelShell)channel).setEnv("LANG", "ja_JP.eucJP");
73 | */
74 | //channel.connect();
75 | channel.connect(60 * 1000);//60 sec timeout
76 | while (!end_loop) {
77 | end_loop = false;
78 | int ret_read = 0;
79 | do {
80 | buff = this.waitCommand();
81 | in = new ByteArrayInputStream(buff);
82 | try {
83 | ret_read = in.read(buff);
84 | //System.out.print(ret_read + " " + new String(buff, 0, ret_read) + "\n");
85 |
86 | try {
87 | streamOut.write(buff, 0, ret_read);
88 | streamOut.flush();
89 | } catch (IOException e) {
90 | end_loop = true;
91 | }
92 |
93 | } catch (IOException ex) {
94 | log.error("Exception while reading keyboard:" + ex);
95 | end_loop = true;
96 | }
97 | } while ((ret_read > 0) && (end_loop == false));
98 | }
99 | } catch (JSchException | IOException ex) {
100 | log.error(ex);
101 | }
102 |
103 | }
104 |
105 | @Override
106 | public void disconnect() throws IOException {
107 | end_loop = true;
108 | if (session != null && session.isConnected()) {
109 | session.disconnect();
110 | }
111 |
112 | }
113 |
114 | public static abstract class MyUserInfo
115 | implements UserInfo, UIKeyboardInteractive {
116 |
117 | public String getPassword() {
118 | return null;
119 | }
120 |
121 | public boolean promptYesNo(String str) {
122 | return false;
123 | }
124 |
125 | public String getPassphrase() {
126 | return null;
127 | }
128 |
129 | public boolean promptPassphrase(String message) {
130 | return false;
131 | }
132 |
133 | public boolean promptPassword(String message) {
134 | return false;
135 | }
136 |
137 | public void showMessage(String message) {
138 | }
139 |
140 | public String[] promptKeyboardInteractive(String destination,
141 | String name,
142 | String instruction,
143 | String[] prompt,
144 | boolean[] echo) {
145 | return null;
146 | }
147 | }
148 |
149 | }
150 |
--------------------------------------------------------------------------------
/src/main/java/com/github/dmtk/StringCrypter.java:
--------------------------------------------------------------------------------
1 | package com.github.dmtk;
2 |
3 | import java.io.IOException;
4 | import org.apache.commons.codec.binary.Base64;
5 | import java.io.UnsupportedEncodingException;
6 | import java.security.InvalidKeyException;
7 | import java.security.NoSuchAlgorithmException;
8 | import javax.crypto.BadPaddingException;
9 | import javax.crypto.Cipher;
10 | import javax.crypto.IllegalBlockSizeException;
11 | import javax.crypto.NoSuchPaddingException;
12 | import javax.crypto.SecretKey;
13 | import org.apache.log4j.Logger;
14 |
15 | public class StringCrypter {
16 |
17 | private final static Logger log = Logger.getLogger(StringCrypter.class);
18 | /**
19 | * Упрощенный конструктор. Создает StringCrypter с ключом
20 | * DESSecretKey (алгоритм шифрования DES) со значением key.
21 | * Ключ key должен иметь длину 8 байт
22 | */
23 | public StringCrypter(byte[] key) {
24 | try {
25 | updateSecretKey(new DESSecretKey(key));
26 | } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException ex) {
27 | throw new IllegalArgumentException(ex.getMessage());
28 | }
29 | }
30 |
31 | public StringCrypter(SecretKey key) throws NoSuchPaddingException,
32 | NoSuchAlgorithmException,
33 | InvalidKeyException {
34 | updateSecretKey(key);
35 | }
36 |
37 | private void updateSecretKey(SecretKey key) throws NoSuchPaddingException,
38 | NoSuchAlgorithmException,
39 | InvalidKeyException {
40 | ecipher = Cipher.getInstance(key.getAlgorithm());
41 | dcipher = Cipher.getInstance(key.getAlgorithm());
42 | ecipher.init(Cipher.ENCRYPT_MODE, key);
43 | dcipher.init(Cipher.DECRYPT_MODE, key);
44 | }
45 |
46 | public static class DESSecretKey implements SecretKey {
47 |
48 | private final byte[] key;
49 |
50 | /**
51 | * ключ должен иметь длину 8 байт
52 | */
53 | public DESSecretKey(byte[] key) {
54 | this.key = key;
55 | }
56 |
57 | @Override
58 | public String getAlgorithm() {
59 | return "DES";
60 | }
61 |
62 | @Override
63 | public String getFormat() {
64 | return "RAW";
65 | }
66 |
67 | @Override
68 | public byte[] getEncoded() {
69 | return key;
70 | }
71 | }
72 |
73 | private Cipher ecipher;
74 | private Cipher dcipher;
75 |
76 | /**
77 | * Функция шифрования
78 | *
79 | * @param str строка открытого текста
80 | * @return зашифрованная строка в формате Base64
81 | */
82 | public String encrypt(String str) {
83 | try {
84 | byte[] utf8 = str.getBytes("UTF8");
85 | byte[] enc = ecipher.doFinal(utf8);
86 | return Base64.encodeBase64String(enc);
87 | } catch (IllegalBlockSizeException | BadPaddingException | UnsupportedEncodingException ex) {
88 | log.error(ex);
89 | }
90 | return null;
91 | }
92 |
93 | /**
94 | * Функция дешифрования
95 | *
96 | * @param str зашифрованная строка в формате Base64
97 | * @return расшифрованная строка
98 | */
99 | public String decrypt(String str) {
100 | try {
101 | byte[] dec = Base64.decodeBase64(str);
102 | byte[] utf8 = dcipher.doFinal(dec);
103 | return new String(utf8, "UTF8");
104 | } catch (IllegalBlockSizeException | BadPaddingException | IOException ex) {
105 | log.error(ex);
106 | }
107 | return null;
108 | }
109 | }
110 |
--------------------------------------------------------------------------------
/src/main/java/com/github/dmtk/Telnet.java:
--------------------------------------------------------------------------------
1 | package com.github.dmtk;
2 |
3 | import java.io.ByteArrayInputStream;
4 | import java.io.FileOutputStream;
5 | import java.io.IOException;
6 | import java.io.InputStream;
7 | import java.io.OutputStream;
8 | import java.io.PrintStream;
9 | import java.util.StringTokenizer;
10 | import org.apache.commons.net.telnet.EchoOptionHandler;
11 | import org.apache.commons.net.telnet.InvalidTelnetOptionException;
12 | import org.apache.commons.net.telnet.SimpleOptionHandler;
13 | import org.apache.commons.net.telnet.SuppressGAOptionHandler;
14 | import org.apache.commons.net.telnet.TelnetClient;
15 | import org.apache.commons.net.telnet.TelnetNotificationHandler;
16 | import org.apache.commons.net.telnet.TerminalTypeOptionHandler;
17 | import org.apache.log4j.Logger;
18 |
19 | public class Telnet extends Terminal implements Runnable, TelnetNotificationHandler {
20 |
21 | private static TelnetClient tc = null;
22 | private final String remoteip;
23 | private final int remoteport;
24 | private final PrintStream out;
25 | private final static Logger log = Logger.getLogger(Telnet.class);
26 | private final int defaultTelnetPort = 23;
27 |
28 | public Telnet(String remoteip, PrintStream out) {
29 |
30 | this.remoteip = remoteip;
31 | this.remoteport = defaultTelnetPort;
32 | this.out = out;
33 |
34 | }
35 |
36 | public Telnet(String remoteip, int remoteport, PrintStream out) {
37 |
38 | this.remoteip = remoteip;
39 | this.remoteport = remoteport;
40 | this.out = out;
41 |
42 | }
43 |
44 | public void execute() {
45 |
46 | end_loop = false;
47 | FileOutputStream fout = null;
48 | try {
49 | fout = new FileOutputStream("spy.log", true);
50 | } catch (IOException ex) {
51 | log.error(ex);
52 | }
53 | tc = new TelnetClient();
54 | TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT100", false, false, true, false);
55 | EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false);
56 | SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true);
57 | try {
58 | tc.addOptionHandler(ttopt);
59 | tc.addOptionHandler(echoopt);
60 | tc.addOptionHandler(gaopt);
61 | } catch (InvalidTelnetOptionException ex) {
62 | log.error(ex);
63 | }
64 |
65 | while (!end_loop) {
66 |
67 | try {
68 | tc.connect(remoteip, remoteport);
69 | Thread reader = new Thread(new Telnet(remoteip, remoteport, out));
70 | tc.registerNotifHandler(new Telnet(remoteip, remoteport, out));
71 | reader.start();
72 | OutputStream outstr = tc.getOutputStream();
73 | byte[] buff = new byte[1024];
74 | ByteArrayInputStream in;
75 | int ret_read = 0;
76 | do {
77 | buff = this.waitCommand();
78 | in = new ByteArrayInputStream(buff);
79 | try {
80 | ret_read = in.read(buff);
81 | //System.out.print(ret_read + " " + new String(buff, 0, ret_read) + "\n");
82 | if (ret_read > 0) {
83 | if ((new String(buff, 0, ret_read)).startsWith("AYT")) {
84 | try {
85 | log.info("AYT response:" + tc.sendAYT(5000));
86 | } catch (IOException e) {
87 | log.error("Exception waiting AYT response: " + e.getMessage());
88 | } catch (IllegalArgumentException ex) {
89 | log.error(ex);
90 | } catch (InterruptedException ex) {
91 | log.error(ex);
92 | }
93 | } else if ((new String(buff, 0, ret_read)).startsWith("OPT")) {
94 | log.info("Status of options:");
95 | for (int ii = 0; ii < 25; ii++) {
96 | log.info("Local Option " + ii + ":" + tc.getLocalOptionState(ii) + " Remote Option " + ii + ":" + tc.getRemoteOptionState(ii));
97 | }
98 | } else if ((new String(buff, 0, ret_read)).startsWith("REGISTER")) {
99 | StringTokenizer st = new StringTokenizer(new String(buff));
100 | try {
101 | st.nextToken();
102 | int opcode = Integer.parseInt(st.nextToken());
103 | boolean initlocal = Boolean.parseBoolean(st.nextToken());
104 | boolean initremote = Boolean.parseBoolean(st.nextToken());
105 | boolean acceptlocal = Boolean.parseBoolean(st.nextToken());
106 | boolean acceptremote = Boolean.parseBoolean(st.nextToken());
107 | SimpleOptionHandler opthand = new SimpleOptionHandler(opcode, initlocal, initremote,
108 | acceptlocal, acceptremote);
109 | tc.addOptionHandler(opthand);
110 | } catch (NumberFormatException | InvalidTelnetOptionException e) {
111 | if (e instanceof InvalidTelnetOptionException) {
112 | log.error("Error registering option: " + e.getMessage());
113 | } else {
114 | log.error("Invalid REGISTER command.");
115 | log.error("Use REGISTER optcode initlocal initremote acceptlocal acceptremote");
116 | log.error("(optcode is an integer.)");
117 | log.error("(initlocal, initremote, acceptlocal, acceptremote are boolean)");
118 | }
119 | }
120 | } else if ((new String(buff, 0, ret_read)).startsWith("UNREGISTER")) {
121 | StringTokenizer st = new StringTokenizer(new String(buff));
122 | try {
123 | st.nextToken();
124 | int opcode = (new Integer(st.nextToken())).intValue();
125 | tc.deleteOptionHandler(opcode);
126 | } catch (Exception e) {
127 | if (e instanceof InvalidTelnetOptionException) {
128 | log.error("Error unregistering option: " + e.getMessage());
129 | } else {
130 | log.error("Invalid UNREGISTER command.");
131 | log.error("Use UNREGISTER optcode");
132 | log.error("(optcode is an integer)");
133 | }
134 | }
135 | } else if ((new String(buff, 0, ret_read)).startsWith("SPY")) {
136 | tc.registerSpyStream(fout);
137 | } else if ((new String(buff, 0, ret_read)).startsWith("UNSPY")) {
138 | tc.stopSpyStream();
139 | } else {
140 | try {
141 | outstr.write(buff, 0, ret_read);
142 | outstr.flush();
143 | } catch (IOException e) {
144 | end_loop = true;
145 | }
146 | }
147 | }
148 | } catch (IOException e) {
149 | log.error("Exception while reading keyboard:" + e.getMessage());
150 | end_loop = true;
151 | }
152 | } while ((ret_read > 0) && (end_loop == false));
153 |
154 | try {
155 | tc.disconnect();
156 | } catch (IOException e) {
157 | log.error("Exception while connecting:" + e.getMessage());
158 |
159 | }
160 | } catch (IOException e) {
161 | log.error("Exception while connecting:" + e.getMessage());
162 |
163 | }
164 | }
165 | }
166 |
167 | /**
168 | * *
169 | * Callback method called when TelnetClient receives an option negotiation
170 | * command.
171 | *
172 | * @param negotiation_code - type of negotiation command received
173 | * (RECEIVED_DO, RECEIVED_DONT, RECEIVED_WILL, RECEIVED_WONT)
174 | *
175 | * @param option_code - code of the option negotiated
176 | *
177 | **
178 | */
179 | // @Override
180 | public void receivedNegotiation(int negotiation_code, int option_code) {
181 | String command = null;
182 | if (negotiation_code == TelnetNotificationHandler.RECEIVED_DO) {
183 | command = "DO";
184 | } else if (negotiation_code == TelnetNotificationHandler.RECEIVED_DONT) {
185 | command = "DONT";
186 | } else if (negotiation_code == TelnetNotificationHandler.RECEIVED_WILL) {
187 | command = "WILL";
188 | } else if (negotiation_code == TelnetNotificationHandler.RECEIVED_WONT) {
189 | command = "WONT";
190 | }
191 | log.info("Received " + command + " for option code " + option_code);
192 | }
193 |
194 | /**
195 | * *
196 | * Reader thread. Reads lines from the TelnetClient and echoes them on the
197 | * screen. *
198 | */
199 | // @Override
200 | public void run() {
201 | InputStream instr = tc.getInputStream();
202 | try {
203 | byte[] buff = new byte[1024];
204 | int ret_read = 0;
205 |
206 | do {
207 | ret_read = instr.read(buff);
208 | if (ret_read > 0) {
209 |
210 | out.print(new String(buff, 0, ret_read));
211 | }
212 | } while (ret_read >= 0);
213 | } catch (Exception e) {
214 | log.error("Exception while reading socket:" + e.getMessage());
215 |
216 | }
217 | try {
218 | tc.disconnect();
219 | } catch (Exception e) {
220 | log.error("Exception while closing telnet:" + e.getMessage());
221 |
222 | }
223 | }
224 |
225 | @Override
226 | public void disconnect() throws IOException {
227 | end_loop = true;
228 | if (tc.isConnected()) {
229 | tc.disconnect();
230 | }
231 |
232 | }
233 |
234 | }
235 |
--------------------------------------------------------------------------------
/src/main/java/com/github/dmtk/Terminal.java:
--------------------------------------------------------------------------------
1 | package com.github.dmtk;
2 |
3 | import java.io.ByteArrayInputStream;
4 | import java.io.IOException;
5 | import java.io.OutputStream;
6 |
7 | import java.nio.CharBuffer;
8 | import java.nio.charset.Charset;
9 | import org.apache.log4j.Logger;
10 |
11 | public abstract class Terminal {
12 |
13 | private final static Logger log = Logger.getLogger(Terminal.class);
14 | protected OutputStream streamOut;
15 | protected boolean end_loop = false;
16 | protected byte[] buff = new byte[1024];
17 | protected ByteArrayInputStream in = new ByteArrayInputStream(buff);
18 | protected String cmd = "";
19 | protected boolean interruptWaiting = false;
20 |
21 | public void sendCommand(String command) {
22 |
23 | cmd = command;
24 | cmd = cmd + "\n";
25 | interruptWaiting = true;
26 |
27 | }
28 |
29 | public byte[] waitCommand() {
30 |
31 | while (!interruptWaiting) {
32 | try {
33 | Thread.sleep(20);
34 | } catch (InterruptedException ex) {
35 | log.error(ex);
36 | }
37 | }
38 | interruptWaiting = false;
39 | char[] chars = cmd.toCharArray();
40 | byte[] bytes = Charset.forName("ASCII").encode(CharBuffer.wrap(chars)).array();//encode chars to bytes
41 | cmd = "";
42 | return bytes;
43 | }
44 |
45 | public abstract void disconnect() throws IOException ;
46 |
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/src/main/java/com/github/dmtk/TextAreaOutputStream.java:
--------------------------------------------------------------------------------
1 | package com.github.dmtk;
2 |
3 | import java.io.IOException;
4 | import java.io.OutputStream;
5 | import javax.swing.JTextArea;
6 |
7 | public class TextAreaOutputStream extends OutputStream {
8 | private JTextArea textArea;
9 |
10 | public TextAreaOutputStream(JTextArea textArea) {
11 | this.textArea = textArea;
12 | }
13 |
14 | @Override
15 | public void write(int b) throws IOException {
16 | // redirects data to the text area
17 | textArea.append(String.valueOf((char)b));
18 | // scrolls the text area to the end of data
19 | textArea.setCaretPosition(textArea.getDocument().getLength());
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/main/java/com/github/dmtk/Vlan.java:
--------------------------------------------------------------------------------
1 | package com.github.dmtk;
2 | import org.apache.log4j.Logger;
3 |
4 | public class Vlan {
5 |
6 | private int vlanId;
7 | private final int defaultVlan = 2;
8 | private final static Logger log = Logger.getLogger(Vlan.class);
9 |
10 | public Vlan(String vlan) {
11 |
12 | try {
13 | intialize(Integer.parseInt(vlan));
14 | } catch (NumberFormatException ex) {
15 | log.error("Wrong VLAN number format" + vlan);
16 | }
17 |
18 | }
19 |
20 | public int getId(){
21 | return vlanId;
22 | }
23 |
24 | public Vlan(int vlan) {
25 | intialize(vlan);
26 | }
27 |
28 | private void intialize(int vlan) {
29 | if (validate(vlan)) {
30 | this.vlanId = vlan;
31 | } else {
32 | this.vlanId = defaultVlan;
33 | log.error("Wrong VLAN number" + vlan);
34 | }
35 | }
36 |
37 | private boolean validate(int vlan) {
38 | return vlan > 0 && vlan < 4094;//VLANs range
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/resources/log4j2.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------