Executing remote shell commands in Java - java

I need to execute some remote commands on unix box using java. For that I have used jsch but the issue is that I need to collect the output of last command.
i wrote the below piece of code:
public static String run(String hostname, String hostPort, String username, String password, String[] commands) throws JSchException, IOException
{
JSch jsch = new JSch();
Session session = jsch.getSession(username, hostname, 22);
session.setPassword(password);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
// System.out.println("Connected");
ChannelExec channel = (ChannelExec) session.openChannel("exec");
BufferedReader in = new BufferedReader(new InputStreamReader(channel.getInputStream()));
StringBuffer sb = new StringBuffer();
for (String s : commands)
{
sb.append(s + ';');
}
String command = sb.toString();
channel.setCommand(command);
channel.connect();
String msg = null;
//String output = "";
StringBuffer output = new StringBuffer();
while ((msg = in.readLine()) != null)
{
//output = output + msg;
output.append(msg);
}
channel.disconnect();
session.disconnect();
// System.out.println("DONE");
return output.toString();
}
In the above code, I am collecting all the command result but i need to collect only result of last command fired.
Please provide your inputs.

Related

Execute perl script in remote server process builder in java

I have an issue where I have application code running in abc server but perl script is located in xyz server.
Due to server compatibility issue I cannot run perl script in abc server.
Can someone please help me how to execute the perl script in xyz server and get the output in java application. I am using processbuilder to execute the script.
I already tried using jsch but no help. Please help me how to achieve solution using process builder.
private StringBuilder runCmd(File folder, ArrayList<String> cmd)
throws IOException {
ProcessBuilder pb = new ProcessBuilder().command(cmd).directory(folder);
Map<String, String> env = pb.environment();
pb.redirectErrorStream(true);
log.debug(pb.command());
Process pr = pb.start();
BufferedReader br = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
try {
int exitVal = pr.waitFor();
log.debug(pb+" value: "+exitVal);
}
catch (InterruptedException e) {
log.error(e.getMessage());
sb.append(e.getMessage());
}
return sb;
}
Jsch code
ProcessBuilder pb = new ProcessBuilder().command(cmd).directory(folder); Map<String, String> env = pb.environment();
String host="xyz";
String user="example";
String password="pw";
String command1="perl abc.perl";
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
Session session=jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig(config);
session.connect();
Channel channel=session.openChannel("exec");
((ChannelExec)channel).setCommand(command1);
channel.setInputStream(null);
((ChannelExec)channel).setErrStream(System.err);
channel.connect();
ByteArrayOutputStream outputBuffer = new ByteArrayOutputStream();
ByteArrayOutputStream errorBuffer = new ByteArrayOutputStream();
StringBuilder sb = new StringBuilder();
InputStream in = channel.getInputStream();
String line;
channel.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
while ((line = reader.readLine()) != null)
{
sb.append(line).append("\n");
}
channel.disconnect();
return sb;

Sqlite3: How to URLEncode query results?

I have a system where it connects to a SMS Gateway.I use sqlite3 to connect to the database of the Gateway. The system connects to the Gateway and retrieves messages then saves it to an Oracle database. My problem is that the format of the messages disappears once I set the values of the message to an object.
Is there any way to encode the message in the query?
I've tried doing this:
SELECT URLENCODE(*) FROM SMSRECV;
I know that this is not a proper function, but I still tried because I really can't find a way
Connecting to the gateway via ssh
private String getSmsDump() {
StringBuilder sb = new StringBuilder();
try {
String command = "sqlite3 /persistent/var/lib/asterisk/db/MyPBX.sqlite \".read /persistent/script/cwms/smsrecv_html.sqlc\"";
String host = this.sshHost;
String user = this.sshUser;
String password = this.sshPassword;
int port = this.sshPort;
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setPassword(password);
session.connect();
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec) channel).setErrStream(System.err);
InputStream input = channel.getInputStream();
channel.connect();
try {
InputStreamReader inputReader = new InputStreamReader(input);
BufferedReader bufferedReader = new BufferedReader(inputReader);
String line = null;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
bufferedReader.close();
inputReader.close();
} catch (Exception ex) {
LOGGER.error("BUFFERED READER ERROR: "+ex);
}
channel.disconnect();
session.disconnect();
} catch (JSchException | IOException ex) {
LOGGER.error("SSH CONNECTION ERROR: "+ex);
}
return sb.toString();
} // end getSmsHtmlDump()
Setting the values to an object:
public List<SmsMessage> getSmsMessages() {
List<SmsMessage> result = new ArrayList();
String smsDump = getSmsDump();
String received = "RECEIVED";
String status = "1";
if (null != smsDump) {
Document messageDump = Jsoup.parse("<html><head></head><body><table>" + smsDump + "</table></body></html>");
Elements rows = messageDump.getElementsByTag("tr");
String hasRead = "0"; //no
// Lambda expression for iterating row elements
rows.stream().map((Element row) -> {
SmsMessage message = new SmsMessage();
Elements cols = row.getElementsByTag("td");
message.setMessageId(cols.get(0).text()); // Message ID
message.setSender(cols.get(1).text()); // Sender
message.setSmsc(cols.get(2).text()); // SMSC
message.setPortId(cols.get(3).text()); // Port ID
message.setContent(cols.get(4).text());
LOGGER.debug(cols.get(4).text());// Content
message.setReceiveTime(cols.get(5).text()); // Receive Time
message.setHasRead(hasRead); // Has Read
message.setTypeOfMessage(received);
message.setMessageStatus(status);
return message;
}).forEachOrdered((message) -> {
result.add(message);
//LOGGER.debug(message.toString());
});
}
return result;
} // end getSmsMessages()
Content of the smsrecv_html.sqlc file:
.mode html
SELECT * FROM SMSRECV;
I just want to set the values to the object without removing the format
Hope you could help me.
Thank you!

How to run Jsch multiple commands from shell-channel using String input instead of console

I am writing a program using JSch library, and have to open a shell channel and execute few commands that are stored in String.
I need to feed the input commands from String variable rather than console.
I have come across a post Jsch : Command Output unavailable
In code given, its working fine for commands like pwd,whoami etc, but its going for a hang when i am trying to do a sudo -u hiveuser -i.
Here is the code:
public static void main(String[] args) throws Exception
{
JSch jsch = new JSch();
String host = "my.host.server";
String user = "myLoginId";
String pswd = "myPASSword";
Session session=jsch.getSession(user,host, 22);
session.setPassword(pswd);
session.setConfig("StrictHostKeyChecking", "no");
session.setConfig("PreferredAuthentications","publickey,keyboard-interactive,password");
session.connect();
System.out.println("Connected");
Channel channel = session.openChannel("shell");
OutputStream ops = channel.getOutputStream();
PrintStream ps = new PrintStream(ops);
channel.connect();
ps.println("sudo -iu hiveuser");
ps.println(pswd);
ps.println("hive");
ps.println("desc table myHiveTable;");
ps.flush();
ps.close();
InputStream in = channel.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
System.out.println("Opening...");
String jarOutput;
while ((jarOutput = reader.readLine()) != null)
System.out.println(jarOutput);
reader.close();
channel.disconnect();
session.disconnect();
}
You could try echoing in the password:
echo password | sudo -iu hiveuser --stdin

How i can read file from unix server after doing some grep operation using java(Jsch)

I have a text file on server with a size of 200 mb.I want reduce the file content using command (grep keyword1 filename.txt|grep -v keyword2) and then read that file in java using Jsch connection.
I solved the issue by below code:-
JSch jsch = new JSch();
Session session = null;
try {
String command="grep 'keyword1' filename.txt|grep -v 'keyword2'";
session = jsch.getSession(userid, servername, serverport);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
session.connect();
Channel channel = session.openChannel("exec");
((ChannelExec)channel).setCommand(command);
channel.connect();
InputStream commandOutput = channel.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(commandOutput));
String line="";
while ((line = br.readLine()) != null)
{
System.out.println(line);
}
br.close();
channel.disconnect();
session.disconnect();
} catch (Exception e) {
e.printStackTrace();
}

JSCH execute command on windows machine and take the output

Here i am executing command on remote windows server from my local windows machine with below code . But i am getting error as
"Unable to execute command or shell on remote system: Failed to
Execute process."
can anybody help me here to come out of this problem?
String user = username;
String pass = password;
String host = ip;
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, 22);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setPassword(pass);
session.connect();
Channel channel = session.openChannel("exec");
channel.connect();
((ChannelExec)channel).setCommand("cmd.exe /c \"echo %cd%\"");
InputStream outputstream_from_the_channel = channel.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(outputstream_from_the_channel));
String jarOutput;
System.out.println("1");
while ((jarOutput = reader.readLine()) != null) {
System.out.println("Inside while loop");
System.out.println(jarOutput + "\n");
}
System.out.println("2");
reader.close();
You need to install cygwin on the host (String host = ip) windows to use jsch.
Follow this site: https://dbaportal.eu/2015/03/05/installing-openssh-cygwin-1-7-35-on-windows-2012-r2/

Categories