Java-JSCH库-需要密码的Run命令 [英] Java - JSCH Library - Run command which expects password
问题描述
我正在编写一个Java程序,该程序在本地Linux主机上运行rsync以将数据复制到远程主机.我正在使用jsch库.我看了jsch的示例,但没有发现任何相关的信息.
I am writing a java program which runs rsync on local Linux host to copy data to remote host. I am using jsch library. I looked at jsch examples, but I didn't find anything relevant.
我无法设置密钥身份验证,因此我期望在rsync命令运行提示输入密码时自动输入远程主机的密码.
I can't setup key authentication, so i was expecting to automated password entry of remote host when rsync command run prompts for the password.
我在网上搜索了一些实现方法,但没有找到任何简单的方法.
I searched online for some ways of doing it, I don't find any easy way of doing it.
以下功能只是执行输入给它的命令,该功能是具有服务器,用户名和密码的类的一部分
Following function just executes command fed to it, this function is part of a class which 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 a channel for 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 the 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 is 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 is invalid %2$s. Exit code parsed %3$s is " +
"not an 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 with {}. Error message {}", this.server, e
.getMessage(), e);
} catch (IOException e) {
logger.error("Exception occurred while creating performing IO with server {}. Error message {}", this
.server, e.getMessage(), e);
} finally {
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 i = inputStream.read(bt, 0, 1024);
if (i < 0) {
break;
}
String str = new String(bt, 0, i);
builder.append(str);
//displays the output of the command executed for debug purpose.
logger.info(str);
if (str.contains(outToFind)) {
logger.info("{} output is found.", outToFind);
return builder.toString();
} else {
logger.info("{} is not matched", str);
}
}
} catch (IOException e) {
logger.error("Exception occurred while creating performing IO with server {}. Error message {}", this
.server, e.getMessage(), e);
throw new Exception(e.getMessage());
}
timeElapsed = timeElapsed + SLEEP_TIME;
if (timeElapsed >= timeoutBeforeExit) {
throw new Exception("Timeout while waiting for output.");
}
try {
Thread.sleep(SLEEP_TIME);
} catch (InterruptedException e) {
logger.warn("Benign exception occurred inputStream thread sleep. Continuing.", e);
}
}
}
推荐答案
您可以尝试以下代码.它会自动读取提供的密码,并继续运行下一个命令.
You can try the below code. It automatically reads the provided password and continue with running the 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 the command, which 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 the password below
out.write(("password\n").getBytes());
out.flush();
//write your commands
PrintStream out1= new PrintStream(out);
out1.println("command1");
out1.println("command2");
...................
out1.flush();
这篇关于Java-JSCH库-需要密码的Run命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!