Java-JSCH Library-Run命令,需要密码

Java-JSCH Library-Run命令,需要密码,java,jsch,Java,Jsch,我正在编写一个java程序,它在本地Linux主机上运行rsync,将数据复制到远程主机。我正在使用jsch库。我查看了jsch示例,但没有发现任何相关内容 Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); JSch jsch = new JSch(); Session session=j

我正在编写一个java程序,它在本地Linux主机上运行rsync,将数据复制到远程主机。我正在使用jsch库。我查看了jsch示例,但没有发现任何相关内容

            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();
我无法设置密钥身份验证,所以我希望在rsync命令运行时自动输入远程主机的密码

            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();
我在网上搜索了一些方法,但没有找到任何简单的方法

            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();
下面的函数只是执行提供给它的命令,这个函数是一个类的一部分,这个类包含服务器、用户名和密码

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);
        }
    }
}
            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();
public int executeCommand(字符串命令)引发异常{
JSch JSch=新的JSch();
会话=空;
通道=空;
int exitCode;
试一试{
//初始化会话
session=jsch.getSession(this.username,this.server,22);
session.setPassword(this.password);
session.setConfig(“StrictHostKeyChecking”、“no”);
setConfig(“首选身份验证”、“公钥、密码”);
//连接
session.connect();
//开辟沟通渠道
channel=session.openChannel(“shell”);
OutputStream ops=channel.getOutputStream();
PrintStream ps=新的PrintStream(ops,true);
channel.connect();
info(“发送命令{}”,命令);
ps.println(命令);
ps.flush();
InputStream InputStream=channel.getInputStream();
processOutput(输入流,“密码:”,超时);
logger.info(“发送密码”);
ps.println(此.targetPassword);
ps.flush();
processOutput(inputStream,“总大小为”,超时);
//获取进程退出代码
字符串exitCodeCommand=“echo$?”;
info(“发送命令{}”,exitCodeCommand);
ps.println(exitCodeCommand);
ps.flush();
字符串exitCodeOutput=processOutput(inputStream,“”,0.5);
字符串[]outputArray=exitCodeOutput.split(System.lineSeparator());
if(输出阵列长度<2){
String msg=String.format(“命令$1%s的退出代码无效%2$s”),exitCodeCommand,
出口(出口);
抛出新异常(msg);
}
试一试{
exitCode=Integer.parseInt(outputArray[1]);
}捕获(NumberFormatException nfe){
错误(“分析{}时发生异常”,outputArray[1],nfe);
String msg=String.format(“命令$1%s的退出代码无效%2$s。解析的退出代码%3$s为”+
“非整数”,exitCodeCommand,exitCodeOutput,outputArray[2]);
抛出新异常(msg);
}
info(“退出代码{}”,exitCode);
inputStream.close();
ps.close();
通道断开();
session.disconnect();
}捕获(JSCHEException e){
logger.error(“使用{}创建会话时发生异常。错误消息{}”),this.server,e
.getMessage(),e);
}捕获(IOE异常){
logger.error(“使用服务器{}创建执行IO时发生异常。错误消息{}”),此
.server,e.getMessage(),e);
}最后{
logger.info(“关闭频道”);
if(channel!=null&&!channel.isClosed()){
通道断开();
}
if(会话!=null){
session.disconnect();
}
}
返回exitCode;
}
私有字符串processOutput(InputStream InputStream、String outToFind、双超时)引发异常{
字节[]bt=新字节[1024];
StringBuilder=新的StringBuilder();
double timeoutBeforeExit=超时*1000*60;
双时间流逝=0;
while(true){
试一试{
while(inputStream.available()>0){
inti=inputStream.read(bt,0,1024);
if(i<0){
打破
}
String str=新字符串(bt,0,i);
附加(str);
//显示为调试目的执行的命令的输出。
记录器信息(str);
if(str.contains(outToFind)){
info(“{}找到输出。”,outToFind);
返回builder.toString();
}否则{
logger.info(“{}不匹配”,str);
}
}
}捕获(IOE异常){
logger.error(“使用服务器{}创建执行IO时发生异常。错误消息{}”),此
.server,e.getMessage(),e);
抛出新异常(如getMessage());
}
时间流逝=时间流逝+睡眠时间;
if(timeappeased>=timeoutbeforexit){
抛出新异常(“等待输出时超时”);
}
试一试{
睡眠(睡眠时间);
}捕捉(中断异常e){
logger.warn(“inputStream线程睡眠时发生良性异常。正在继续。”,e);
}
}
}

您可以尝试以下代码。它会自动读取提供的密码并继续运行下一个命令

            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();

我建议您考虑在JSCH之上使用一个类似于WEB的库。在维基百科上查看备选方案列表:,以及我自己的实现。