V2.2.0 Execute Linux Command when talking to echo component

master
Ng Yat Yan 1 month ago
parent 30bf0350b7
commit f5c1b7000f

@ -4,7 +4,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.example.sshd</groupId>
<artifactId>echo-sshd-server</artifactId>
<version>2.1.0</version>
<version>2.2.0</version>
<name>ECHO SSH SERVER</name>
<description>Learning Apache Mina SSHD library</description>
<parent>

@ -31,6 +31,9 @@ public class EchoComponent extends AbstractComponent {
@Autowired
XmppComponentConfig xmppComponentConfig;
@Autowired
ReplyService replyService;
@Autowired
@Qualifier("userAdminCache")
private volatile Cache<String, Message> userAdminCache;
@ -111,7 +114,7 @@ public class EchoComponent extends AbstractComponent {
doEcho(inMsg, "chgpasswd <username> <new_password>");
break;
default:
doEcho(inMsg, null);
doEcho(inMsg, replyService.executeShellCommand(inMsg.getBody().trim()));
break;
}
}

@ -112,19 +112,7 @@ public class ReplyService {
String reply = hashReplies.getProperty(o.get().getRight(), "").replace("\\r", "\r").replace("\\n", "\n")
.replace("\\t", "\t");
if (reply.isEmpty()) {
logger.info("[{}] Execute cmd for real: {} ({})", cmdHash, command.trim(), o.get());
ByteArrayOutputStream tempOut = new ByteArrayOutputStream();
try {
CommandLine cmdLine = CommandLine.parse(command.trim());
DefaultExecutor executor = DefaultExecutor.builder().get();
PumpStreamHandler streamHandler = new PumpStreamHandler(tempOut);
executor.setStreamHandler(streamHandler);
int exitValue = executor.execute(cmdLine);
logger.info("[{}] Result: {} ({})", cmdHash, command.trim(), exitValue);
reply = new String(tempOut.toByteArray()).replace("\n", "\r\n");
} catch (ExecuteException e) {
logger.info("[{}] Execute cmd failed: {} ({})", cmdHash, command.trim(), o.get(), e);
}
reply = executeShellCommand(command.trim());
out.write(String.format("\r\n%s\r\n%s", reply, prompt).getBytes());
} else {
logger.info("[{}] Known pattern detected: {} ({})", cmdHash, command.trim(), o.get());
@ -139,4 +127,22 @@ public class ReplyService {
}
return false;
}
public String executeShellCommand(String command) throws IOException {
String cmdHash = DigestUtils.md5Hex(command.trim()).toUpperCase();
logger.info("[{}] Execute cmd for real: {}", cmdHash, command.trim());
ByteArrayOutputStream tempOut = new ByteArrayOutputStream();
try {
CommandLine cmdLine = CommandLine.parse(command.trim());
DefaultExecutor executor = DefaultExecutor.builder().get();
PumpStreamHandler streamHandler = new PumpStreamHandler(tempOut);
executor.setStreamHandler(streamHandler);
int exitValue = executor.execute(cmdLine);
logger.info("[{}] Result: {} ({})", cmdHash, command.trim(), exitValue);
return new String(tempOut.toByteArray()).replace("\n", "\r\n");
} catch (ExecuteException e) {
logger.info("[{}] Execute cmd failed: {}", cmdHash, command.trim(), e);
}
return null;
}
}

Loading…
Cancel
Save