use of com.jcraft.jsch.Channel 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.Channel 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.Channel 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);
}
}
use of com.jcraft.jsch.Channel in project GNS by MobilityFirst.
the class SFTPUpload method authenticateSftp.
private static ChannelSftp authenticateSftp(String user, String host, File keyFile) throws JSchException {
Session session;
Channel channel;
JSch jsch = new JSch();
session = SSHClient.authenticateWithKey(jsch, user, host, keyFile);
session.connect();
channel = session.openChannel("sftp");
channel.connect();
return (ChannelSftp) channel;
}
use of com.jcraft.jsch.Channel in project hutool by looly.
the class JschUtil method openSftp.
/**
* 打开SFTP连接
*
* @param session Session会话
* @return {@link ChannelSftp}
* @since 4.0.3
*/
public static ChannelSftp openSftp(Session session) {
Channel channel;
try {
channel = session.openChannel("sftp");
channel.connect();
} catch (JSchException e) {
throw new JschRuntimeException(e);
}
return (ChannelSftp) channel;
}
Aggregations