use of com.jcraft.jsch.JSch in project GNS by MobilityFirst.
the class UserAuthPubKey method main.
/**
*
* @param arg
*/
public static void main(String[] arg) {
try {
JSch jsch = new JSch();
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Choose your privatekey(ex. ~/.ssh/id_dsa)");
chooser.setFileHidingEnabled(false);
int returnVal = chooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose " + chooser.getSelectedFile().getAbsolutePath() + ".");
// , "passphrase"
jsch.addIdentity(// , "passphrase"
chooser.getSelectedFile().getAbsolutePath());
}
String host = null;
if (arg.length > 0) {
host = arg[0];
} else {
host = JOptionPane.showInputDialog("Enter username@hostname", System.getProperty("user.name") + "@localhost");
}
String user = host.substring(0, host.indexOf('@'));
host = host.substring(host.indexOf('@') + 1);
Session session = jsch.getSession(user, host, 22);
// username and passphrase will be given via UserInfo interface.
UserInfo ui = new UserInfoPrompted();
session.setUserInfo(ui);
session.connect();
Channel channel = session.openChannel("shell");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect();
} catch (HeadlessException | JSchException e) {
System.out.println(e);
}
}
use of com.jcraft.jsch.JSch in project azure-tools-for-java by Microsoft.
the class AddNewEmulatorForm method preEmulatorSetupCheck.
private void preEmulatorSetupCheck() {
isCarryOnNextStep = true;
errorMessage = null;
emulatorSetupLog = new StringBuilder();
errorMessageField.setText("");
emulatorLogPanel.setVisible(false);
clusterName = clusterNameField.getText().trim();
userName = userNameField.getText().trim();
password = String.valueOf(passwordField.getPassword());
livyEndpoint = livyEndpointField.getText().trim().replaceAll("/+$", "");
sshEndpoint = sshEndpointField.getText().trim().replaceAll("/+$", "");
sparkHistoryEndpoint = sparkHistoryEndpointField.getText().trim().replaceAll("/+$", "");
ambariEndpoint = ambariEndpointField.getText().trim().replaceAll("/+$", "");
try {
host = new URI(sshEndpoint).getHost();
sshPort = new URI(sshEndpoint).getPort();
jsch = new JSch();
config = new Properties();
config.put("StrictHostKeyChecking", "no");
} catch (Exception exception) {
errorMessage = exception.getMessage();
isCarryOnNextStep = false;
}
if (isCarryOnNextStep && StringHelper.isNullOrWhiteSpace(clusterName) || StringHelper.isNullOrWhiteSpace(sshEndpoint) || StringHelper.isNullOrWhiteSpace(livyEndpoint) || StringHelper.isNullOrWhiteSpace(userName) || StringHelper.isNullOrWhiteSpace(password) || StringHelper.isNullOrWhiteSpace(sparkHistoryEndpoint) || StringHelper.isNullOrWhiteSpace(ambariEndpoint)) {
errorMessage = "Cluster Name, Endpoint fields, User Name, or Password shouldn't be empty";
isCarryOnNextStep = false;
} else if (isCarryOnNextStep && ClusterManagerEx.getInstance().isEmulatorClusterExist(clusterName)) {
errorMessage = "Cluster Name already exist in current list";
isCarryOnNextStep = false;
} else if (isCarryOnNextStep && !checkSshEndpoint()) {
errorMessage = "Could not ssh to emulator, please check username, password and ssh port.";
isCarryOnNextStep = false;
}
}
use of com.jcraft.jsch.JSch in project voltdb by VoltDB.
the class SSHTools method long_running_command.
public ProcessData long_running_command(String hostname, String[] command, String processName, OutputHandler handler) {
try {
JSch jsch = new JSch();
// Set the private key
if (null != m_keyFile)
jsch.addIdentity(m_keyFile);
Session session = jsch.getSession(m_username, hostname, 22);
// To avoid the UnknownHostKey issue
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
// timeout after 5 seconds.
session.connect(5000);
return new ProcessData(processName, handler, session, stringify(command));
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
use of com.jcraft.jsch.JSch in project voltdb by VoltDB.
the class SSHTools method ScpTo.
// The Jsch method for SCP to.
// This code is direcly copied from the Jsch SCP sample program.
public boolean ScpTo(String local_file, String user, String key, String host, String remote_file) {
FileInputStream fis = null;
try {
boolean ptimestamp = true;
String command = "scp " + (ptimestamp ? "-p" : "") + " -t " + 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);
// timeout after 5 seconds
session.connect(5000);
// exec 'scp -t 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();
if (checkAck(in) != 0) {
return false;
}
File _lfile = new File(local_file);
if (ptimestamp) {
command = "T " + (_lfile.lastModified() / 1000) + " 0";
// The access time should be sent here,
// but it is not accessible with JavaAPI ;-<
command += (" " + (_lfile.lastModified() / 1000) + " 0\n");
out.write(command.getBytes());
out.flush();
if (checkAck(in) != 0) {
return false;
}
}
// send "C0644 filesize filename", where filename should not include '/'
long filesize = _lfile.length();
command = "C0644 " + filesize + " ";
if (local_file.lastIndexOf('/') > 0) {
command += local_file.substring(local_file.lastIndexOf('/') + 1);
} else {
command += local_file;
}
command += "\n";
out.write(command.getBytes());
out.flush();
if (checkAck(in) != 0) {
return false;
}
// send a content of lfile
fis = new FileInputStream(local_file);
byte[] buf = new byte[1024];
while (true) {
int len = fis.read(buf, 0, buf.length);
if (len <= 0)
break;
//out.flush();
out.write(buf, 0, len);
}
fis.close();
fis = null;
// send '\0'
buf[0] = 0;
out.write(buf, 0, 1);
out.flush();
if (checkAck(in) != 0) {
return false;
}
out.close();
channel.disconnect();
session.disconnect();
} catch (Exception e) {
System.out.println(e);
try {
if (fis != null)
fis.close();
} catch (Exception ee) {
}
return false;
}
return true;
}
use of com.jcraft.jsch.JSch in project nifi by apache.
the class SFTPTransfer method getChannel.
private ChannelSftp getChannel(final FlowFile flowFile) throws IOException {
if (sftp != null) {
String sessionhost = session.getHost();
String desthost = ctx.getProperty(HOSTNAME).evaluateAttributeExpressions(flowFile).getValue();
if (sessionhost.equals(desthost)) {
// destination matches so we can keep our current session
return sftp;
} else {
// this flowFile is going to a different destination, reset session
close();
}
}
final JSch jsch = new JSch();
try {
final String username = ctx.getProperty(USERNAME).evaluateAttributeExpressions(flowFile).getValue();
final Session session = jsch.getSession(username, ctx.getProperty(HOSTNAME).evaluateAttributeExpressions(flowFile).getValue(), ctx.getProperty(PORT).evaluateAttributeExpressions(flowFile).asInteger().intValue());
final String hostKeyVal = ctx.getProperty(HOST_KEY_FILE).getValue();
if (hostKeyVal != null) {
jsch.setKnownHosts(hostKeyVal);
}
final Properties properties = new Properties();
properties.setProperty("StrictHostKeyChecking", ctx.getProperty(STRICT_HOST_KEY_CHECKING).asBoolean() ? "yes" : "no");
properties.setProperty("PreferredAuthentications", "publickey,password,keyboard-interactive");
final PropertyValue compressionValue = ctx.getProperty(FileTransfer.USE_COMPRESSION);
if (compressionValue != null && "true".equalsIgnoreCase(compressionValue.getValue())) {
properties.setProperty("compression.s2c", "zlib@openssh.com,zlib,none");
properties.setProperty("compression.c2s", "zlib@openssh.com,zlib,none");
} else {
properties.setProperty("compression.s2c", "none");
properties.setProperty("compression.c2s", "none");
}
session.setConfig(properties);
final String privateKeyFile = ctx.getProperty(PRIVATE_KEY_PATH).evaluateAttributeExpressions(flowFile).getValue();
if (privateKeyFile != null) {
jsch.addIdentity(privateKeyFile, ctx.getProperty(PRIVATE_KEY_PASSPHRASE).evaluateAttributeExpressions(flowFile).getValue());
}
final String password = ctx.getProperty(FileTransfer.PASSWORD).evaluateAttributeExpressions(flowFile).getValue();
if (password != null) {
session.setPassword(password);
}
final int connectionTimeoutMillis = ctx.getProperty(FileTransfer.CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue();
session.setTimeout(connectionTimeoutMillis);
session.connect();
this.session = session;
this.closed = false;
sftp = (ChannelSftp) session.openChannel("sftp");
sftp.connect(connectionTimeoutMillis);
session.setTimeout(ctx.getProperty(FileTransfer.DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
if (!ctx.getProperty(USE_KEEPALIVE_ON_TIMEOUT).asBoolean()) {
// do not send keepalive message on SocketTimeoutException
session.setServerAliveCountMax(0);
}
try {
this.homeDir = sftp.getHome();
} catch (SftpException e) {
// For some combination of server configuration and user home directory, getHome() can fail with "2: File not found"
// Since homeDir is only used tor SEND provenance event transit uri, this is harmless. Log and continue.
logger.debug("Failed to retrieve {} home directory due to {}", new Object[] { username, e.getMessage() });
}
return sftp;
} catch (JSchException e) {
throw new IOException("Failed to obtain connection to remote host due to " + e.toString(), e);
}
}
Aggregations