use of com.jcraft.jsch.ChannelExec in project che by eclipse.
the class JschSshClient method createProcess.
@Override
public JschSshProcess createProcess(String commandLine) throws MachineException {
try {
ChannelExec exec = (ChannelExec) session.openChannel("exec");
exec.setCommand(commandLine);
exec.setPty(true);
envVars.entrySet().stream().forEach(envVariableEntry -> exec.setEnv(envVariableEntry.getKey(), envVariableEntry.getValue()));
return new JschSshProcess(exec);
} catch (JSchException e) {
throw new MachineException("Can't establish connection to perform command execution in ssh machine. Error: " + e.getLocalizedMessage(), e);
}
}
use of com.jcraft.jsch.ChannelExec in project voltdb by VoltDB.
the class SFTPSession method exec.
public String exec(String command, int timeout) {
ChannelExec channel = null;
BufferedReader outStrBufRdr = null;
BufferedReader errStrBufRdr = null;
StringBuilder result = new StringBuilder(2048);
try {
try {
channel = (ChannelExec) m_session.openChannel("exec");
} catch (JSchException jex) {
throw new SSHException("opening ssh exec channel", jex);
}
// Direct stdout output of command
try {
InputStream out = channel.getInputStream();
InputStreamReader outStrRdr = new InputStreamReader(out, "UTF-8");
outStrBufRdr = new BufferedReader(outStrRdr);
} catch (IOException ioex) {
throw new SSHException("geting exec channel input stream", ioex);
}
// Direct stderr output of command
try {
InputStream err = channel.getErrStream();
InputStreamReader errStrRdr = new InputStreamReader(err, "UTF-8");
errStrBufRdr = new BufferedReader(errStrRdr);
} catch (IOException ioex) {
throw new SSHException("getting exec channel error stream", ioex);
}
channel.setCommand(command);
StringBuffer stdout = new StringBuffer();
StringBuffer stderr = new StringBuffer();
try {
channel.connect(timeout);
int retries = timeout / 100;
while (!channel.isClosed() && retries-- > 0) {
// Read from both streams here so that they are not blocked,
// if they are blocked because the buffer is full, channel.isClosed() will never
// be true.
int ch;
try {
while (outStrBufRdr.ready() && (ch = outStrBufRdr.read()) > -1) {
stdout.append((char) ch);
}
} catch (IOException ioex) {
throw new SSHException("capturing '" + command + "' output", ioex);
}
try {
while (errStrBufRdr.ready() && (ch = errStrBufRdr.read()) > -1) {
stderr.append((char) ch);
}
} catch (IOException ioex) {
throw new SSHException("capturing '" + command + "' error", ioex);
}
try {
Thread.sleep(100);
} catch (InterruptedException ignoreIt) {
}
}
if (retries < 0) {
throw new SSHException("'" + command + "' timed out");
}
} catch (JSchException jex) {
throw new SSHException("executing '" + command + "'", jex);
}
// In case there's still some more stuff in the buffers, read them
int ch;
try {
while ((ch = outStrBufRdr.read()) > -1) {
stdout.append((char) ch);
}
} catch (IOException ioex) {
throw new SSHException("capturing '" + command + "' output", ioex);
}
try {
while ((ch = errStrBufRdr.read()) > -1) {
stderr.append((char) ch);
}
} catch (IOException ioex) {
throw new SSHException("capturing '" + command + "' error", ioex);
}
if (stderr.length() > 0) {
throw new SSHException(stderr.toString());
}
result.append(stdout.toString());
result.append(stderr.toString());
} finally {
if (outStrBufRdr != null)
try {
outStrBufRdr.close();
} catch (Exception ignoreIt) {
}
if (errStrBufRdr != null)
try {
errStrBufRdr.close();
} catch (Exception ignoreIt) {
}
if (channel != null && channel.isConnected()) {
// Shutdown the connection
channel.disconnect();
}
}
return result.toString();
}
use of com.jcraft.jsch.ChannelExec in project voltdb by VoltDB.
the class SSHTools method cmdSSH.
/*
* The code from here to the end of the file is code that integrates with an external
* SSH library (JSCH, http://www.jcraft.com/jsch/). If you wish to replaces this
* library, these are the methods that need to be re-worked.
*/
public String cmdSSH(String user, String password, String key, String host, String command) {
StringBuilder result = new StringBuilder(2048);
try {
JSch jsch = new JSch();
// Set the private key
if (null != key)
jsch.addIdentity(key);
Session session = jsch.getSession(user, host, 22);
session.setTimeout(5000);
// To avoid the UnknownHostKey issue
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
if (password != null && !password.trim().isEmpty()) {
session.setPassword(password);
}
session.connect();
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
// Direct stderr output of command
InputStream err = ((ChannelExec) channel).getErrStream();
InputStreamReader errStrRdr = new InputStreamReader(err, "UTF-8");
Reader errStrBufRdr = new BufferedReader(errStrRdr);
// Direct stdout output of command
InputStream out = channel.getInputStream();
InputStreamReader outStrRdr = new InputStreamReader(out, "UTF-8");
Reader outStrBufRdr = new BufferedReader(outStrRdr);
StringBuffer stdout = new StringBuffer();
StringBuffer stderr = new StringBuffer();
// timeout after 5 seconds
channel.connect(5000);
while (true) {
if (channel.isClosed()) {
break;
}
// Read from both streams here so that they are not blocked,
// if they are blocked because the buffer is full, channel.isClosed() will never
// be true.
int ch;
while (outStrBufRdr.ready() && (ch = outStrBufRdr.read()) > -1) {
stdout.append((char) ch);
}
while (errStrBufRdr.ready() && (ch = errStrBufRdr.read()) > -1) {
stderr.append((char) ch);
}
try {
Thread.sleep(100);
} catch (InterruptedException ie) {
}
}
// In case there's still some more stuff in the buffers, read them
int ch;
while ((ch = outStrBufRdr.read()) > -1) {
stdout.append((char) ch);
}
while ((ch = errStrBufRdr.read()) > -1) {
stderr.append((char) ch);
}
// After the command is executed, gather the results (both stdin and stderr).
result.append(stdout.toString());
result.append(stderr.toString());
// Shutdown the connection
channel.disconnect();
session.disconnect();
} catch (Throwable e) {
e.printStackTrace();
// Return empty string if we can't connect.
}
return result.toString();
}
use of com.jcraft.jsch.ChannelExec in project voltdb by VoltDB.
the class SSHTools method ScpFrom.
// The Jsch method for SCP from.
// This code is directly copied from the Jsch SCP sample program. Error handling has been modified by VoltDB.
public boolean ScpFrom(String user, String key, String host, String remote_file, String local_file) {
FileOutputStream fos = null;
try {
String prefix = null;
if (new File(local_file).isDirectory()) {
prefix = local_file + File.separator;
}
String command = "scp -f " + remote_file;
cmdLog.debug("CMD: '" + command + "'");
JSch jsch = new JSch();
// Set the private key
if (null != key)
jsch.addIdentity(key);
Session session = jsch.getSession(user, host, 22);
// To avoid the UnknownHostKey issue
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
// exec 'scp -f rfile' remotely
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
// get I/O streams for remote scp
OutputStream out = channel.getOutputStream();
InputStream in = channel.getInputStream();
channel.connect();
byte[] buf = new byte[1024];
// send '\0'
buf[0] = 0;
out.write(buf, 0, 1);
out.flush();
while (true) {
int c = checkAck(in);
if (c != 'C') {
break;
}
// read '0644 '
in.read(buf, 0, 5);
long filesize = 0L;
while (true) {
if (in.read(buf, 0, 1) < 0) {
// error
break;
}
if (buf[0] == ' ')
break;
filesize = filesize * 10L + (buf[0] - '0');
}
String file = null;
for (int i = 0; ; i++) {
in.read(buf, i, 1);
if (buf[i] == (byte) 0x0a) {
file = new String(buf, 0, i);
break;
}
}
String destination_file = prefix == null ? local_file : prefix + file;
cmdLog.debug("CMD: scp to local file '" + destination_file + "'");
// send '\0'
buf[0] = 0;
out.write(buf, 0, 1);
out.flush();
// read a content of lfile
fos = new FileOutputStream(destination_file);
int foo;
while (true) {
if (buf.length < filesize)
foo = buf.length;
else
foo = (int) filesize;
foo = in.read(buf, 0, foo);
if (foo < 0) {
// error
break;
}
fos.write(buf, 0, foo);
filesize -= foo;
if (filesize == 0L)
break;
}
fos.close();
fos = null;
if (checkAck(in) != 0) {
cmdLog.debug("CMD: scp checkAck failed");
System.out.println("checkAck did not equal zero.");
return false;
}
// send '\0'
buf[0] = 0;
out.write(buf, 0, 1);
out.flush();
}
session.disconnect();
} catch (Exception e) {
System.out.println(e);
cmdLog.debug("CMD: scp failed with exception: " + e.toString());
return false;
} finally {
try {
if (fos != null)
fos.close();
} catch (Exception ee) {
}
}
return true;
}
use of com.jcraft.jsch.ChannelExec in project GNS by MobilityFirst.
the class Sudo method main.
/**
*
* @param arg
*/
public static void main(String[] arg) {
try {
JSch jsch = new JSch();
Session session = SSHClient.authenticateWithKey(jsch, null, null, null);
UserInfo ui = new UserInfoPrompted();
session.setUserInfo(ui);
session.connect();
String command = JOptionPane.showInputDialog("Enter command, execed with sudo", "printenv SUDO_USER");
String sudo_pass = null;
{
JTextField passwordField = new JPasswordField(8);
Object[] ob = { passwordField };
int result = JOptionPane.showConfirmDialog(null, ob, "Enter password for sudo", JOptionPane.OK_CANCEL_OPTION);
if (result != JOptionPane.OK_OPTION) {
System.exit(-1);
}
sudo_pass = passwordField.getText();
}
Channel channel = session.openChannel("exec");
// man sudo
// -S The -S (stdin) option causes sudo to read the password from the
// standard input instead of the terminal device.
// -p The -p (prompt) option allows you to override the default
// password prompt and use a custom one.
((ChannelExec) channel).setCommand("sudo -S -p '' " + command);
InputStream in = channel.getInputStream();
OutputStream out = channel.getOutputStream();
((ChannelExec) channel).setErrStream(System.err);
((ChannelExec) channel).setPty(true);
channel.connect();
out.write((sudo_pass + "\n").getBytes());
out.flush();
byte[] tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0) {
break;
}
System.out.print(new String(tmp, 0, i));
}
if (channel.isClosed()) {
System.out.println("exit-status: " + channel.getExitStatus());
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
}
}
channel.disconnect();
session.disconnect();
} catch (JSchException | HeadlessException | IOException e) {
System.out.println(e);
}
}
Aggregations