Java code to run command on remote Linux with sesu access - java

I need java code that logs into linux box with my credentials, then do a sesu , and then execute a shell script. Permission to execute the shell script if for only sesu user, hence sesu-ing after login is critical. I used te following code which can help me execute a command with my credential scope, however, I need sesu login following my login. Please suggest a way.
I tried adding the sesu command in teh command list, but it prompts for a password. I want a way to pass the password as well and completly automate it.
import java.io.InputStream;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class SSHCommandExecutor {
/** * #param args */
public static void main(String[] args) {
String host = "xxxxxxx";
String user = "xxxxxxx";
String password = "xxxxxxx";
String command1 = "cd /test; ./test.sh";
try {
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();
System.out.println("Connected");
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command1);
channel.setInputStream(null);
((ChannelExec) channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
channel.connect();
byte[] tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0)
break;
System.out.print(new String(tmp, 0, i));
}
if (channel.isClosed()) {
System.out.println("exit-status: " + channel.getExitStatus());
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {}
}
channel.disconnect();
session.disconnect();
System.out.println("DONE");
} catch (Exception e) {
e.printStackTrace();
}
}
}

Variant A: Using JSch all the way
This minimal script (test.sh) requests an input from stdin before putting out one line of data:
#!/bin/bash
echo -n "Is this a good question (y/n)? "
read answer
if echo "$answer" | grep -iq "^y" ;then
echo Yes
else
echo No
fi
So it should be equivalent to your call requesting a password to be given. Now have a look at this code on how to send data into that process
String command1 = "cd /home/jan; ./test.sh";
try {
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();
System.out.println("Connected");
ChannelExec channel = (ChannelExec)session.openChannel("exec");
OutputStream o = channel.getOutputStream();
PrintWriter pw = new PrintWriter(o);
InputStream in = channel.getInputStream();
((ChannelExec) channel).setCommand(command1);
channel.connect();
// 1 - Reading the prompt to input password
byte[] buf = new byte[255];
int len = in.read(buf);
System.out.println(new String(buf,0,len));
// 2 - Send (password) data and flush stream
pw.println("y");
pw.flush();
// 3 - Read result
BufferedReader br = new BufferedReader(new InputStreamReader(in));
System.out.println(br.readLine());
// 4 - Clean up
channel.disconnect();
session.disconnect();
Variant B: Shell magic
String command1 = "cd /test; echo 'password' | ./test.sh";
or
String command1 = "cd /test; ./test.sh <<< 'password'";
(of cause you'd need to specify correct password there)
To run remote script with root privileges even if login user does not have them see here:
https://askubuntu.com/questions/155791/how-do-i-sudo-a-command-in-a-script-without-being-asked-for-a-password

Related

Unable to access the cmd prompt in remote machine using openchannel in java

I'm trying to access the cmd prompt in administrator mode and run a batch file in the remote machine,but right now I'm not able to access the cmd prompt through openchannel. Did anybody tried to access it from remote machine in java?
Here is the code
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
session = jsch.getSession(user, ip, 22);
session.setPassword(password);
session.setTimeout(timeOut);
session.setConfig(config);
session.connect();
System.out.println("session connected");
//open command prompt to run the command = "C:\\executeBatchFile.bat" file
Channel channel = (ChannelExec) session.openChannel("exec");
((ChannelExec)channel).setCommand("cmd.exe /c \"echo %cd%\"\\executeBatchFile.bat");
channel.connect();
InputStream outputstream_from_the_channel = channel.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(outputstream_from_the_channel));
String jarOutput;
while ((jarOutput = reader.readLine()) != null)
{
System.out.println("Inside while loop");
System.out.println(jarOutput + "\n");
}
reader.close();
session.disconnect();
Expected behavior :set command should run as an administrator(though I have logged in as admin),come back to the c:drive (cd) and execute the batch file ie; C:executeBatchFile.bat
Actual behaviour : command gives the user path(not as admin) when I print the jarOutput. ie; C:\Users\Admin\executeBatchFile.bat
could you suggest any solution on the same?
This has been resolved using PsExec command instead of JSCH
String pscommand=E:\\Tool\\psexec -u user -p pwd \\\\ip -s -d cmd.exe /c C:\\executescript.bat
process = Runtime.getRuntime().exec(pscommand);
InputStream es = process.getErrorStream();
BufferedReader errReader = new BufferedReader(new InputStreamReader(es));
String line;
// Read STDOUT into a buffer.
while ((line = errReader.readLine()) != null)
{
system.out.println(line);
}
Could any one tell me how to open the cmd prompt in administrator mode(I logged in using admin credentials only but still it does not open in admin mode).Here I need to run the script in administrator.

How to stop the tomcat server on linux using java and JSch?

I have a requirement in automation where I need to stop the tomcat server located at Linux.. How can I do it?. I am trying multiple code-snippets using JSch but those are not working as expected. Can someone please help me here?
Here is my sample code -
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
session = jsch.getSession(user, host, port);
session.setPassword(password);
session.setConfig(config);
session.connect();
System.out.println("CONNECTED!");
String process = serverGetprocess();
LOG.info("ACTAUL SERVER PROCESS "+process);
commandStopServer = "kill -9" + process;
LOG.info(commandStopServer);
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(commandStopServer);
channel.setInputStream(null);
channel.setOutputStream(System.out, true);
((ChannelExec) channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
channel.connect();
Thread.sleep(1000);
byte[] tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0)
break;
System.out.print(new String(tmp, 0, i));
}
if (channel.isClosed()) {
System.out.println("exit-status: " + channel.getExitStatus());
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
LOG.info("Inside catch of channel closing!");
}
}
channel.disconnect();
return true;
Here is the code to put within set command "pkill -9 -f tomcat" i.e;
((ChannelExec) channel).setCommand("pkill -9 -f tomcat");

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 to write on a file inside a server using Jsch exec

I tried some commands such as
echo "Your text here" | ssh hostname 'cat >> output.txt'
but it didnt work.
How can I write in a file inside the server using this exec code or just the ssh command that I will put to String command.
public class TestWrite{
private static final String user = "username here";
private static final String host = "host here";
private static final String password = "pass here";
public static void main(String[] arg){
try{
JSch jsch=new JSch();
Session session=jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
String command = "Command here";
Channel channel=session.openChannel("exec");
((ChannelExec)channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec)channel).setErrStream(System.err);
InputStream in=channel.getInputStream();
channel.connect();
byte[] tmp=new byte[1024];
while(true){
while(in.available()>0){
int i=in.read(tmp, 0, 1024);
if(i<0)break;
System.out.print(new String(tmp, 0, i));
}
if(channel.isClosed()){
if(in.available()>0) continue;
System.out.println("exit-status: "+channel.getExitStatus());
break;
}
try{Thread.sleep(1000);}catch(Exception ee){}
}
channel.disconnect();
session.disconnect();
}
catch(Exception e){
System.out.println(e);
}
}
}
You can write to a file with
echo "your text here" > file
You don't need ssh because Jsch takes its place.
Try a command like:
ssh hostname 'echo "Your text here" >> output.txt'

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