登录Linux计算机并执行多个命令

时间:2017-11-27 10:51:24

标签: java linux perl ssh automation

我正在尝试通过java从远程计算机(Windows 7)登录并执行一组命令到linux机器,

(经销商ID:RedHatEnterpriseServer
描述:红帽企业Linux服务器版本5.10
发布:5.10)

请查看Perl脚本,该脚本运行正常,需要实现相同的功能。

use strict;  
use warnings; 

use Net::SSH::Expect; 

my $ssh = Net::SSH::Expect->new(   
    host     => "host123",  
    password => "passwd",  
    user     => "username",  
    raw_pty  => 1,  
    timeout  => 1, 
);
$ssh->login();

$ssh->exec("su - root");  
$ssh->exec("passwd");  
$ssh->exec("su - user");  
$ssh->exec("command1");  
$ssh->exec("subcommand"); 

my $output = $ssh->exec("subcommand 2");  
warn "$output\n";  
$ssh->exec("\n");

my $output2 = $ssh->exec("subcommand 3");  
warn "$output2\n";  
$ssh->exec("\n")

类似的功能需要在java的帮助下执行.. 目前我已经编写了以下java代码

import java.io.InputStreamReader;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

public void sshExecute() throws Exception {

    String username = "username";
    String password = "passwd";
    String hostname = "host123";
    logger.setLevel(Level.INFO);

    Object lastCommandOutput = null;
    logger.info("starting connection with " + hostname);

    Connection connection = new Connection(hostname);
    logger.info("connection object created..");

    connection.connect();
    connection.authenticateWithPassword(username, password);

    Session session = connection.openSession();
    InputStream stdout = new StreamGobbler(session.getStdout());
    BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(stdout));
    logger.info("connected");

    String tempCommand = "su - root";
    String Pswd = "passwd";
    logger.info("sending command: " + tempCommand);

    session.execCommand(tempCommand + Pswd);
    TimeUnit.SECONDS.sleep(5);

    session.execCommand("su - user");

    // Get output
    StringBuffer sb = new StringBuffer();

    while (true) {
        String line = stdoutReader.readLine();
        if (line == null)
            break;
        sb.append(line + "\n");
    }

    String output = sb.toString();
    lastCommandOutput = output;
    logger.info("got output: " + output);

    stdoutReader.close();
}

直到第session.execCommand("su - user");行才能正常工作。那里, 它给出了一个错误:

java.io.IOException: A remote execution has already started.  java.lang.Error: java.io.IOException: A remote execution has already started at com.user1.test.Assert.fail(Assert.java:35)

如何登录两次,即su -root然后su-user,以及为什么我们不能多次使用execCommand进行会话?有没有其他方法可以实现此目的而不是execCommand,以实现上述功能?

0 个答案:

没有答案
相关问题