use of com.jcraft.jsch.Channel in project litle-sdk-for-java by Vantiv.
the class Communication method receiveLitleRequestResponseFileFromSFTP.
/**
* Grabs the response file from Litle's sFTP server. This method is blocking! It will continue to poll until the timeout has elapsed
* or the file has been retrieved!
* @param requestFile
* @param responseFile
* @param configuration
* @throws IOException
*/
public void receiveLitleRequestResponseFileFromSFTP(File requestFile, File responseFile, Properties configuration) throws IOException {
String username = configuration.getProperty("sftpUsername");
String password = configuration.getProperty("sftpPassword");
String hostname = configuration.getProperty("batchHost");
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = null;
Session session = null;
try {
jsch = new JSch();
session = jsch.getSession(username, hostname);
session.setConfig(config);
session.setPassword(password);
session.connect();
} catch (JSchException e) {
throw new LitleBatchException("Exception connection to Litle", e);
}
Channel channel = null;
try {
channel = session.openChannel("sftp");
channel.connect();
} catch (JSchException e) {
throw new LitleBatchException("Exception connection to Litle", e);
}
ChannelSftp sftp = (ChannelSftp) channel;
Long start = System.currentTimeMillis();
Long timeout = Long.parseLong(configuration.getProperty("sftpTimeout"));
System.out.println("Retrieving from sFTP...");
while (System.currentTimeMillis() - start < timeout) {
try {
Thread.sleep(45000);
} catch (InterruptedException e) {
e.printStackTrace();
}
boolean success = true;
try {
sftp.get("outbound/" + requestFile.getName() + ".asc", responseFile.getAbsolutePath());
} catch (SftpException e) {
success = false;
System.out.println(e);
}
if (success) {
try {
sftp.rm("outbound/" + requestFile.getName() + ".asc");
} catch (SftpException e) {
throw new LitleBatchException("Exception SFTP operation", e);
}
break;
}
System.out.print(".");
}
boolean printxml = configuration.getProperty("printxml") != null && configuration.getProperty("printxml").equalsIgnoreCase("true");
if (printxml) {
BufferedReader reader = new BufferedReader(new FileReader(responseFile));
String line = "";
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
channel.disconnect();
session.disconnect();
}
use of com.jcraft.jsch.Channel in project opentest by mcdcorp.
the class GetFromSftp method run.
@Override
public void run() {
super.run();
String sftpHost = this.readStringArgument("sftpHost");
Integer sftpPort = this.readIntArgument("sftpPort", 22);
String userName = this.readStringArgument("userName");
String password = this.readStringArgument("password");
String sourceDir = this.readStringArgument("sourceDir");
String sourceFile = this.readStringArgument("sourceFile");
String destinationDir = this.readStringArgument("destinationDir");
String destinationFileName = this.readStringArgument("destinationFile", sourceFile);
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
try {
JSch jsch = new JSch();
session = jsch.getSession(userName, sftpHost, sftpPort);
session.setPassword(password);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
this.log.trace("Connected to SFTP host");
channel = session.openChannel("sftp");
channel.connect();
this.log.trace("The SFTP channel was opened and connected");
channelSftp = (ChannelSftp) channel;
channelSftp.cd(sourceDir);
File destinationFile = new File(destinationDir, destinationFileName);
FileOutputStream fileOutputStream = new FileOutputStream(destinationFile);
channelSftp.get(sourceFile, fileOutputStream);
fileOutputStream.close();
} catch (Exception ex) {
throw new RuntimeException("SFTP transfer failed", ex);
} finally {
if (channelSftp != null) {
channelSftp.exit();
}
if (channel != null) {
channel.disconnect();
}
if (session != null) {
session.disconnect();
}
}
}
use of com.jcraft.jsch.Channel in project hutool by looly.
the class JschUtil method openShell.
/**
* 打开Shell连接
*
* @param session Session会话
* @return {@link ChannelShell}
* @since 4.0.3
*/
public static ChannelShell openShell(Session session) {
Channel channel;
try {
channel = session.openChannel("shell");
channel.connect();
} catch (JSchException e) {
throw new JschRuntimeException(e);
}
return (ChannelShell) channel;
}
use of com.jcraft.jsch.Channel in project KeyBox by skavanagh.
the class SSHUtil method addPubKey.
/**
* distributes authorized keys for host system
*
* @param hostSystem object contains host system information
* @param session an established SSH session
* @param appPublicKey application public key value
* @return status of key distribution
*/
public static HostSystem addPubKey(HostSystem hostSystem, Session session, String appPublicKey) {
try {
String authorizedKeys = hostSystem.getAuthorizedKeys().replaceAll("~\\/|~", "");
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand("cat " + authorizedKeys);
((ChannelExec) channel).setErrStream(System.err);
channel.setInputStream(null);
InputStream in = channel.getInputStream();
InputStreamReader is = new InputStreamReader(in);
BufferedReader reader = new BufferedReader(is);
channel.connect(CHANNEL_TIMEOUT);
String appPubKey = appPublicKey.replace("\n", "").trim();
StringBuilder existingKeysBuilder = new StringBuilder();
String currentKey;
while ((currentKey = reader.readLine()) != null) {
existingKeysBuilder.append(currentKey).append("\n");
}
String existingKeys = existingKeysBuilder.toString();
existingKeys = existingKeys.replaceAll("\\n$", "");
reader.close();
// disconnect
channel.disconnect();
StringBuilder newKeysBuilder = new StringBuilder();
if (keyManagementEnabled) {
// get keys assigned to system
List<String> assignedKeys = PublicKeyDB.getPublicKeysForSystem(hostSystem.getId());
for (String key : assignedKeys) {
newKeysBuilder.append(key.replace("\n", "").trim()).append("\n");
}
newKeysBuilder.append(appPubKey);
} else {
if (existingKeys.indexOf(appPubKey) < 0) {
newKeysBuilder.append(existingKeys).append("\n").append(appPubKey);
} else {
newKeysBuilder.append(existingKeys);
}
}
String newKeys = newKeysBuilder.toString();
if (!newKeys.equals(existingKeys)) {
log.info("Update Public Keys ==> " + newKeys);
channel = session.openChannel("exec");
((ChannelExec) channel).setCommand("echo '" + newKeys + "' > " + authorizedKeys + "; chmod 600 " + authorizedKeys);
((ChannelExec) channel).setErrStream(System.err);
channel.setInputStream(null);
channel.connect(CHANNEL_TIMEOUT);
// disconnect
channel.disconnect();
}
} catch (JSchException | SQLException | IOException | GeneralSecurityException ex) {
log.error(ex.toString(), ex);
}
return hostSystem;
}
use of com.jcraft.jsch.Channel in project KeyBox by skavanagh.
the class SSHUtil method openSSHTermOnSystem.
/**
* open new ssh session on host system
*
* @param passphrase key passphrase for instance
* @param password password for instance
* @param userId user id
* @param sessionId session id
* @param hostSystem host system
* @param userSessionMap user session map
* @return status of systems
*/
public static HostSystem openSSHTermOnSystem(String passphrase, String password, Long userId, Long sessionId, HostSystem hostSystem, Map<Long, UserSchSessions> userSessionMap) throws SQLException, GeneralSecurityException {
JSch jsch = new JSch();
int instanceId = getNextInstanceId(sessionId, userSessionMap);
hostSystem.setStatusCd(HostSystem.SUCCESS_STATUS);
hostSystem.setInstanceId(instanceId);
SchSession schSession = null;
try {
ApplicationKey appKey = PrivateKeyDB.getApplicationKey();
// check to see if passphrase has been provided
if (passphrase == null || passphrase.trim().equals("")) {
passphrase = appKey.getPassphrase();
// check for null inorder to use key without passphrase
if (passphrase == null) {
passphrase = "";
}
}
// add private key
jsch.addIdentity(appKey.getId().toString(), appKey.getPrivateKey().trim().getBytes(), appKey.getPublicKey().getBytes(), passphrase.getBytes());
// create session
Session session = jsch.getSession(hostSystem.getUser(), hostSystem.getHost(), hostSystem.getPort());
// set password if it exists
if (password != null && !password.trim().equals("")) {
session.setPassword(password);
}
session.setConfig("StrictHostKeyChecking", "no");
session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
session.setServerAliveInterval(SERVER_ALIVE_INTERVAL);
session.connect(SESSION_TIMEOUT);
Channel channel = session.openChannel("shell");
if ("true".equals(AppConfig.getProperty("agentForwarding"))) {
((ChannelShell) channel).setAgentForwarding(true);
}
((ChannelShell) channel).setPtyType("xterm");
InputStream outFromChannel = channel.getInputStream();
// new session output
SessionOutput sessionOutput = new SessionOutput(sessionId, hostSystem);
Runnable run = new SecureShellTask(sessionOutput, outFromChannel);
Thread thread = new Thread(run);
thread.start();
OutputStream inputToChannel = channel.getOutputStream();
PrintStream commander = new PrintStream(inputToChannel, true);
channel.connect();
schSession = new SchSession();
schSession.setUserId(userId);
schSession.setSession(session);
schSession.setChannel(channel);
schSession.setCommander(commander);
schSession.setInputToChannel(inputToChannel);
schSession.setOutFromChannel(outFromChannel);
schSession.setHostSystem(hostSystem);
// refresh keys for session
addPubKey(hostSystem, session, appKey.getPublicKey());
} catch (JSchException | IOException | GeneralSecurityException ex) {
log.info(ex.toString(), ex);
hostSystem.setErrorMsg(ex.getMessage());
if (ex.getMessage().toLowerCase().contains("userauth fail")) {
hostSystem.setStatusCd(HostSystem.PUBLIC_KEY_FAIL_STATUS);
} else if (ex.getMessage().toLowerCase().contains("auth fail") || ex.getMessage().toLowerCase().contains("auth cancel")) {
hostSystem.setStatusCd(HostSystem.AUTH_FAIL_STATUS);
} else if (ex.getMessage().toLowerCase().contains("unknownhostexception")) {
hostSystem.setErrorMsg("DNS Lookup Failed");
hostSystem.setStatusCd(HostSystem.HOST_FAIL_STATUS);
} else {
hostSystem.setStatusCd(HostSystem.GENERIC_FAIL_STATUS);
}
}
// add session to map
if (hostSystem.getStatusCd().equals(HostSystem.SUCCESS_STATUS)) {
// get the server maps for user
UserSchSessions userSchSessions = userSessionMap.get(sessionId);
// if no user session create a new one
if (userSchSessions == null) {
userSchSessions = new UserSchSessions();
}
Map<Integer, SchSession> schSessionMap = userSchSessions.getSchSessionMap();
// add server information
schSessionMap.put(instanceId, schSession);
userSchSessions.setSchSessionMap(schSessionMap);
// add back to map
userSessionMap.put(sessionId, userSchSessions);
}
SystemStatusDB.updateSystemStatus(hostSystem, userId);
SystemDB.updateSystem(hostSystem);
return hostSystem;
}
Aggregations