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;
Related
This question already has answers here:
Certain Unix commands fail with "... not found", when executed through Java using JSch
(3 answers)
Closed 3 years ago.
I am trying to develop a small application that allows me to send certain commands by SSH to a remote server. If I try it from the Linux terminal or from the Windows Command Prompt it works without problems, but when I do it from my Java application it always responds with a status code of 255.
I have disabled the firewall and I have changed the port where I have listening SSH on the server to 22, because I use another, but nothing works. It does not throw me exceptions or anything and if it connects without problems. Any ideas?
I have tried with the sshj and JSch libraries and with both I have the same problem.
ForwardAgent is turn off
sshj example
private void sshj() throws Exception {
SSHClient ssh = new SSHClient();
ssh.addHostKeyVerifier((s, i, publicKey) -> true);
ssh.connect("host", 22);
Session session = null;
try {
ssh.authPassword("username", "password");
session = ssh.startSession();
Session.Command cmd = session.exec("command");
System.out.println(IOUtils.readFully(cmd.getInputStream()).toString());
cmd.join(5, TimeUnit.SECONDS);
System.out.println("Exit status: " + cmd.getExitStatus());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (session != null) {
session.close();
}
ssh.disconnect();
}
}
JSch example
private static void jsch() throws Exception {
JSch js = new JSch();
Session s = js.getSession("username", "host", 22);
s.setPassword("password");
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
s.setConfig(config);
s.connect();
Channel c = s.openChannel("exec");
ChannelExec ce = (ChannelExec) c;
ce.setCommand("command");
ce.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(ce.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
ce.disconnect();
s.disconnect();
System.out.println("Exit status: " + ce.getExitStatus());
}
change to code so that you get the inputStream before doing connect
InputStream in = ce.getInputStream();
ce.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
Also, the getSession is wrong as it should be
public Session getSession(String username,
String host,
int port)
edit
The below code works for me
JSch js = new JSch();
Session s = js.getSession("username", "127.0.0.1", 22);
s.setPassword("password");
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
s.setConfig(config);
s.connect();
Channel c = s.openChannel("exec");
ChannelExec ce = (ChannelExec) c;
ce.setCommand("uptime");
InputStream in = ce.getInputStream();
ce.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
ce.disconnect();
s.disconnect();
System.out.println("Exit status: " + ce.getExitStatus());
output
10:26:08 up 149 days, 58 min, 3 users, load average: 0.61, 0.68, 0.68
Exit status: 0
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
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();
}
I am trying to use jsch to connect to a remote switch and run some command and extract the output.
I am able to connect to the switch using , however the command output is not available in the inputstream. Maybe i am not doing it the right way. Here's the code
session = jsch.getSession("user", "10.0.0.0", 22);
session.setPassword("somepwd");
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
System.out.println("connected to remote host");
Channel channel = session.openChannel("shell");
OutputStream ops = channel.getOutputStream();
PrintStream ps = new PrintStream(ops);
channel.connect();
ps.println("show version");
ps.flush();
ps.close();
InputStream in=channel.getInputStream();
byte[] bt=new byte[1024];
while(in.available()>0)
{
int i=in.read(bt, 0, 1024);
if(i<0)
break;
String str=new String(bt, 0, i);
//displays the output of the command executed.
System.out.print(str);
}
channel.disconnect();
session.disconnect();
When i debug the inputStream.isAvailable() always returns zero suggesting that there is no output from the command.
TIA!
Please try the code below - tested and working
Channel channel = session.openChannel("shell");
OutputStream ops = channel.getOutputStream();
PrintStream ps = new PrintStream(ops);
channel.connect();
ps.println("pwd");
ps.println("exit");
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();
Output -
Opening...
user#host:~> pwd
/home/user
user#host:~>
user#host:~> exit
logout
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.