Java - JSCH Library - Run command which expects password -
i writing java program runs rsync on local linux host copy data remote host. using jsch library. looked @ jsch examples, didn't find relevant.
i can't setup key authentication, expecting automated password entry of remote host when rsync command run prompts password.
i searched online ways of doing it, don't find easy way of doing it.
following function executes command fed it, function part of class has server, username, password
public int executecommand(string command) throws exception { jsch jsch = new jsch(); session session = null; channel channel = null; int exitcode; try { //initialize session session = jsch.getsession(this.username, this.server, 22); session.setpassword(this.password); session.setconfig("stricthostkeychecking", "no"); session.setconfig("preferredauthentications", "publickey,password"); //connect session.connect(); //open channel communication channel = session.openchannel("shell"); outputstream ops = channel.getoutputstream(); printstream ps = new printstream(ops, true); channel.connect(); logger.info("sending command {} ",command); ps.println(command); ps.flush(); inputstream inputstream = channel.getinputstream(); processoutput(inputstream, "password:", timeout); logger.info("sending password."); ps.println(this.targetpassword); ps.flush(); processoutput(inputstream, "total size is", timeout); //get process exit code string exitcodecommand = "echo $?"; logger.info("sending command {} ",exitcodecommand); ps.println(exitcodecommand); ps.flush(); string exitcodeoutput = processoutput(inputstream, "", 0.5); string[] outputarray = exitcodeoutput.split(system.lineseparator()); if (outputarray.length < 2) { string msg = string.format("exit code of command $1%s invalid %2$s", exitcodecommand, exitcodeoutput); throw new exception(msg); } try { exitcode = integer.parseint(outputarray[1]); } catch (numberformatexception nfe) { logger.error("exception occurred while parsing {}", outputarray[1], nfe); string msg = string.format("exit code of command $1%s invalid %2$s. exit code parsed %3$s " + "not integer", exitcodecommand, exitcodeoutput, outputarray[2]); throw new exception(msg); } logger.info("exit code {}", exitcode); inputstream.close(); ps.close(); channel.disconnect(); session.disconnect(); } catch (jschexception e) { logger.error("exception occurred while creating session {}. error message {}", this.server, e .getmessage(), e); } catch (ioexception e) { logger.error("exception occurred while creating performing io server {}. error message {}", .server, e.getmessage(), e); } { logger.info("closing channels"); if (channel != null && !channel.isclosed()) { channel.disconnect(); } if (session != null) { session.disconnect(); } } return exitcode; } private string processoutput(inputstream inputstream, string outtofind, double timeout) throws exception { byte[] bt = new byte[1024]; stringbuilder builder = new stringbuilder(); double timeoutbeforeexit = timeout * 1000 * 60; double timeelapsed = 0; while (true) { try { while (inputstream.available() > 0) { int = inputstream.read(bt, 0, 1024); if (i < 0) { break; } string str = new string(bt, 0, i); builder.append(str); //displays output of command executed debug purpose. logger.info(str); if (str.contains(outtofind)) { logger.info("{} output found.", outtofind); return builder.tostring(); } else { logger.info("{} not matched", str); } } } catch (ioexception e) { logger.error("exception occurred while creating performing io server {}. error message {}", .server, e.getmessage(), e); throw new exception(e.getmessage()); } timeelapsed = timeelapsed + sleep_time; if (timeelapsed >= timeoutbeforeexit) { throw new exception("timeout while waiting output."); } try { thread.sleep(sleep_time); } catch (interruptedexception e) { logger.warn("benign exception occurred inputstream thread sleep. continuing.", e); } } }
you can try below code. automatically reads provided password , continue running next commands.
properties config = new 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"); //write command, expects password ((channelexec)channel).setcommand("command"); ((channelexec)channel).seterrstream(system.err); ((channelexec)channel).setpty(true); system.out.println("password taken"); inputstream in=channel.getinputstream(); channel.connect(); outputstream out=channel.getoutputstream(); //give password below out.write(("password\n").getbytes()); out.flush(); //write commands printstream out1= new printstream(out); out1.println("command1"); out1.println("command2"); ................... out1.flush();
Comments
Post a Comment