问题
I am trying to login and execute a set of commands through java from my remote computer (windows 7) into linux machine,
(Distributor ID: RedHatEnterpriseServer
Description: Red Hat Enterprise Linux Server release 5.10
Release: 5.10 )
Please look into the Perl script , which is working perfectly, same functionality needs to be achieved.
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")
similar function need to be executed with the help of java.. currently i have written the following java code
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();
}
This is working fine till line session.execCommand("su - user");. There,
it gives an error as :
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)
How to login twice, i.e su -root and then su - user, and also why can't we use execCommand more than once for a session? Is there any other way to achieve this instead of execCommand, to achieve the above functionality?
来源:https://stackoverflow.com/questions/47509180/log-into-a-linux-machine-and-execute-multiple-commands