After I run below script from java-
suu -t -r "reason" <user_name>
It prompted me for password and I entered it. After that the program was running but not executing any further commands.
I want to impersonate on Linux machine through Java (Jsch library). I am not getting any errors, but after the password is given, Its successfully logging in and then no commands are being executed.
This is the link I followed to write code- https://linuxconfig.org/executing-commands-on-a-remote-machine-from-java-with-jsch
After running suu command, I want to read a file. Without running suu, I will not have access to that path. Any help for this issue will be more appreciated :)
Here is my snippet- [![enter image description here][1]][1]
Thanks in advance!
Below is code I used-
public class SSHConn {
static Session session;
static String suCmds = "suu -t -u \"reason\" simba";
static String[] commands = {"whoami", suCmds};
public static void main(String[] args) throws Exception {
open();
runCmd(commands);
close();
}
public static void runCmd(String[] commands) throws JSchException, IOException {
for (String cmd : commands) {
System.out.println("\nExecuting command: " + cmd);
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(cmd);
InputStream in = channel.getInputStream();
OutputStream out = channel.getOutputStream();
channel.connect();
//passing creds only when you switch user
if (cmd.startsWith("suu -")) {
System.out.println("Setting suPasswd now....");
out.write((Constants.suPasswd + "\n").getBytes());
out.flush();
System.out.println("Flushed suPasswd to cli...");
}
captureCmdOutput(in, channel);
channel.setInputStream(null);
channel.disconnect();
}
}
public static void captureCmdOutput(InputStream in, Channel channel) throws IOException {
System.out.println("Capturing cmdOutput now...");
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()) {
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
System.out.println(ee.getMessage());
}
}
}
public static void open() throws JSchException {
JSch jSch = new JSch();
session = jSch.getSession(Constants.userId, Constants.host, 22);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setPassword(Constants.userPasswd);
System.out.println("Connecting SSH to " + Constants.host + " - Please wait for few seconds... ");
session.connect();
System.out.println("Connected!\n");
}
public static void close() {
session.disconnect();
System.out.println("\nDisconnected channel and session");
}}