How to use JSch method of com.consol.citrus.ssh.client.SshClient class

Best Citrus code snippet using com.consol.citrus.ssh.client.SshClient.JSch

Source:SshClient.java Github

copy

Full Screen

...40 private CorrelationManager<Message> correlationManager;41 // Session for the SSH communication42 private Session session;43 // SSH implementation44 private JSch jsch = new JSch();45 /**46 * Default constructor initializing endpoint configuration.47 */48 public SshClient() {49 this(new SshEndpointConfiguration());50 }51 /**52 * Default constructor using endpoint configuration.53 * @param endpointConfiguration54 */55 protected SshClient(SshEndpointConfiguration endpointConfiguration) {56 super(endpointConfiguration);57 this.correlationManager = new PollingCorrelationManager<>(endpointConfiguration, "Reply message did not arrive yet");58 }59 @Override60 public SshEndpointConfiguration getEndpointConfiguration() {61 return (SshEndpointConfiguration) super.getEndpointConfiguration();62 }63 /**64 * Send a message as SSH request. The message format is created from65 * {@link com.consol.citrus.ssh.server.SshServer}.66 *67 * @param message the message object to send.68 * @param context69 */70 public void send(Message message, TestContext context) {71 String correlationKeyName = getEndpointConfiguration().getCorrelator().getCorrelationKeyName(getName());72 String correlationKey = getEndpointConfiguration().getCorrelator().getCorrelationKey(message);73 correlationManager.saveCorrelationKey(correlationKeyName, correlationKey, context);74 SshRequest request = (SshRequest) getEndpointConfiguration().getMessageConverter().convertOutbound(message, getEndpointConfiguration(), context);75 if (getEndpointConfiguration().isStrictHostChecking()) {76 setKnownHosts();77 }78 String rUser = getRemoteUser(message);79 connect(rUser);80 ChannelExec channelExec = null;81 ByteArrayOutputStream outStream = new ByteArrayOutputStream();82 ByteArrayOutputStream errStream = new ByteArrayOutputStream();83 int rc;84 try {85 channelExec = openChannelExec();86 channelExec.setErrStream(errStream);87 channelExec.setOutputStream(outStream);88 channelExec.setCommand(request.getCommand());89 doConnect(channelExec);90 if (request.getStdin() != null) {91 sendStandardInput(channelExec, request.getStdin());92 }93 waitCommandToFinish(channelExec);94 rc = channelExec.getExitStatus();95 } finally {96 if (channelExec != null && channelExec.isConnected()) {97 channelExec.disconnect();98 }99 disconnect();100 }101 SshResponse sshResp = new SshResponse(outStream.toString(),errStream.toString(),rc);102 Message response = getEndpointConfiguration().getMessageConverter().convertInbound(sshResp, getEndpointConfiguration(), context)103 .setHeader("user", rUser);104 correlationManager.store(correlationKey, response);105 }106 @Override107 public Message receive(TestContext context) {108 return receive(correlationManager.getCorrelationKey(109 getEndpointConfiguration().getCorrelator().getCorrelationKeyName(getName()), context), context);110 }111 @Override112 public Message receive(String selector, TestContext context) {113 return receive(selector, context, getEndpointConfiguration().getTimeout());114 }115 @Override116 public Message receive(TestContext context, long timeout) {117 return receive(correlationManager.getCorrelationKey(118 getEndpointConfiguration().getCorrelator().getCorrelationKeyName(getName()), context), context, timeout);119 }120 @Override121 public Message receive(String selector, TestContext context, long timeout) {122 Message message = correlationManager.find(selector, timeout);123 if (message == null) {124 throw new ActionTimeoutException("Action timeout while receiving synchronous reply message from ssh server");125 }126 return message;127 }128 @Override129 public Producer createProducer() {130 return this;131 }132 @Override133 public SelectiveConsumer createConsumer() {134 return this;135 }136 private void connect(String rUser) {137 if (session == null || !session.isConnected()) {138 try {139 if (StringUtils.hasText(getEndpointConfiguration().getPrivateKeyPath())) {140 jsch.addIdentity(getPrivateKeyPath(), getEndpointConfiguration().getPrivateKeyPassword());141 }142 } catch (JSchException e) {143 throw new CitrusRuntimeException("Cannot add private key " + getEndpointConfiguration().getPrivateKeyPath() + ": " + e,e);144 } catch (IOException e) {145 throw new CitrusRuntimeException("Cannot open private key file " + getEndpointConfiguration().getPrivateKeyPath() + ": " + e,e);146 }147 try {148 session = jsch.getSession(rUser, getEndpointConfiguration().getHost(), getEndpointConfiguration().getPort());149 if (StringUtils.hasText(getEndpointConfiguration().getPassword())) {150 session.setUserInfo(new UserInfoWithPlainPassword(getEndpointConfiguration().getPassword()));151 session.setPassword(getEndpointConfiguration().getPassword());152 }153 session.setConfig(KnownHostsServerKeyVerifier.STRICT_CHECKING_OPTION, getEndpointConfiguration().isStrictHostChecking() ? "yes" : "no");154 session.connect();155 } catch (JSchException e) {156 throw new CitrusRuntimeException("Cannot connect via SSH: " + e,e);157 }158 }159 }160 private void disconnect() {161 if (session.isConnected()) {162 session.disconnect();163 }164 }165 private ChannelExec openChannelExec() throws CitrusRuntimeException {166 ChannelExec channelExec;167 try {168 channelExec = (ChannelExec) session.openChannel("exec");169 } catch (JSchException e) {170 throw new CitrusRuntimeException("Cannot open EXEC SSH channel: " + e,e);171 }172 return channelExec;173 }174 private void waitCommandToFinish(ChannelExec pCh) {175 final long until = System.currentTimeMillis() + getEndpointConfiguration().getCommandTimeout();176 try {177 while (!pCh.isClosed() && System.currentTimeMillis() < until) {178 Thread.sleep(250);179 }180 } catch (InterruptedException e) {181 throw new RuntimeException("Interrupted", e);182 }183 if (!pCh.isClosed()) {184 throw new CitrusRuntimeException("Timeout: Channel not finished within " + getEndpointConfiguration().getCommandTimeout() + " ms");185 }186 }187 private void sendStandardInput(ChannelExec pCh, String pInput) {188 OutputStream os = null;189 try {190 os = pCh.getOutputStream();191 os.write(pInput.getBytes());192 } catch (IOException e) {193 throw new CitrusRuntimeException("Cannot write to standard input of SSH channel: " + e,e);194 } finally {195 if (os != null) {196 try {197 os.close();198 } catch (IOException e) {199 // best try200 }201 }202 }203 }204 private void doConnect(ChannelExec pCh) {205 try {206 if (getEndpointConfiguration().getConnectionTimeout() != 0) {207 pCh.connect(getEndpointConfiguration().getConnectionTimeout());208 } else {209 pCh.connect();210 }211 } catch (JSchException e) {212 throw new CitrusRuntimeException("Cannot connect EXEC SSH channel: " + e,e);213 }214 }215 private String getRemoteUser(Message message) {216 String rUser = (String) message.getHeader("user");217 if (rUser == null) {218 // Use default uses219 rUser = getEndpointConfiguration().getUser();220 }221 if (rUser == null) {222 throw new CitrusRuntimeException("No user given for connecting to SSH server");223 }224 return rUser;225 }226 private void setKnownHosts() {227 if (getEndpointConfiguration().getKnownHosts() == null) {228 throw new CitrusRuntimeException("Strict host checking is enabled but no knownHosts given");229 }230 try {231 InputStream khIs = FileUtils.getFileResource(getEndpointConfiguration().getKnownHosts()).getInputStream();232 if (khIs == null) {233 throw new CitrusRuntimeException("Cannot find knownHosts at " + getEndpointConfiguration().getKnownHosts());234 }235 jsch.setKnownHosts(khIs);236 } catch (JSchException e) {237 throw new CitrusRuntimeException("Cannot add known hosts from " + getEndpointConfiguration().getKnownHosts() + ": " + e,e);238 } catch (IOException e) {239 throw new CitrusRuntimeException("Cannot find known hosts file " + getEndpointConfiguration().getKnownHosts() + ": " + e,e);240 }241 }242 private String getPrivateKeyPath() throws IOException {243 if (!StringUtils.hasText(getEndpointConfiguration().getPrivateKeyPath())) {244 return null;245 } else if (getEndpointConfiguration().getPrivateKeyPath().startsWith(ResourceUtils.CLASSPATH_URL_PREFIX)) {246 File priv = File.createTempFile("citrus-ssh","priv");247 InputStream is = getClass().getClassLoader().getResourceAsStream(getEndpointConfiguration().getPrivateKeyPath().substring(ResourceUtils.CLASSPATH_URL_PREFIX.length()));248 if (is == null) {249 throw new CitrusRuntimeException("No private key found at " + getEndpointConfiguration().getPrivateKeyPath());250 }251 FileCopyUtils.copy(is, new FileOutputStream(priv));252 return priv.getAbsolutePath();253 } else {254 return getEndpointConfiguration().getPrivateKeyPath();255 }256 }257 // UserInfo which simply returns a plain password258 private static class UserInfoWithPlainPassword implements UserInfo {259 private String password;260 public UserInfoWithPlainPassword(String pPassword) {261 password = pPassword;262 }263 public String getPassphrase() {264 return null;265 }266 public String getPassword() {267 return password;268 }269 public boolean promptPassword(String message) {270 return false;271 }272 public boolean promptPassphrase(String message) {273 return false;274 }275 public boolean promptYesNo(String message) {276 return false;277 }278 public void showMessage(String message) {279 }280 }281 /**282 * Gets the JSch implementation.283 * @return284 */285 public JSch getJsch() {286 return jsch;287 }288 /**289 * Sets the JSch implementation.290 * @param jsch291 */292 public void setJsch(JSch jsch) {293 this.jsch = jsch;294 }295 /**296 * Sets the correlation manager.297 * @param correlationManager298 */299 public void setCorrelationManager(CorrelationManager<Message> correlationManager) {300 this.correlationManager = correlationManager;301 }302}...

Full Screen

Full Screen

Source:SshClientTest.java Github

copy

Full Screen

...38 */39public class SshClientTest extends AbstractTestNGUnitTest {40 private static final String COMMAND = "ls";41 private static final String STDIN = "Hello world";42 private JSch jsch;43 private SshClient client;44 private ByteArrayOutputStream outStream;45 private Session session;46 private ChannelExec channel;47 private static final int CONNECTTION_TIMEOUT = 50;48 @BeforeMethod49 public void setup() throws JSchException {50 jsch = Mockito.mock(JSch.class);51 SshEndpointConfiguration endpointConfiguration = new SshEndpointConfiguration();52 client = new SshClient(endpointConfiguration);53 client.setJsch(jsch);54 endpointConfiguration.setHost("planck");55 endpointConfiguration.setUser("roland");56 endpointConfiguration.setPort(1968);57 endpointConfiguration.setConnectionTimeout(CONNECTTION_TIMEOUT);58 endpointConfiguration.setCommandTimeout(2 * 60 * 1000);59 session = Mockito.mock(Session.class);60 when(jsch.getSession("roland","planck",1968)).thenReturn(session);61 channel = Mockito.mock(ChannelExec.class);62 ReflectionTestUtils.setField(client, "jsch", jsch);63 outStream = new ByteArrayOutputStream();64 }65 @Test(expectedExceptions = CitrusRuntimeException.class,expectedExceptionsMessageRegExp = ".*user.*")66 public void noUser() {67 client.getEndpointConfiguration().setUser(null);68 send();69 }70 @Test(expectedExceptions = CitrusRuntimeException.class,expectedExceptionsMessageRegExp = ".*knownHosts.*")71 public void strictHostCheckingWithoutKnownHosts() throws JSchException {72 strictHostChecking(true, null);73 send();74 }75 @Test(expectedExceptions = CitrusRuntimeException.class,expectedExceptionsMessageRegExp = ".*blaHosts.*")76 public void strictHostCheckingWithFaultyKnownHosts() throws JSchException {77 strictHostChecking(true, "classpath:/com/consol/citrus/ssh/blaHosts");78 send();79 }80 @Test(expectedExceptions = CitrusRuntimeException.class,expectedExceptionsMessageRegExp = ".*/does/not/exist.*")81 public void strictHostCheckingWithFaultyKnownHosts2() throws JSchException {82 strictHostChecking(true, "/file/that/does/not/exist");83 send();84 }85 @Test86 public void strictHostCheckingWithKnownHosts() throws JSchException, IOException {87 strictHostChecking(true, "classpath:com/consol/citrus/ssh/knownHosts");88 jsch.setKnownHosts(isA(InputStream.class));89 standardChannelPrepAndSend();90 }91 private void standardChannelPrepAndSend() throws JSchException, IOException {92 session.connect();93 prepareChannel(COMMAND, 0);94 disconnect();95 send();96 }97 @Test(expectedExceptions = CitrusRuntimeException.class, expectedExceptionsMessageRegExp = ".*/that/does/not/exist.*")98 public void withUnknownPrivateKey() throws JSchException {99 strictHostChecking(false,null);100 client.getEndpointConfiguration().setPrivateKeyPath("/file/that/does/not/exist");101 doThrow(new JSchException("No such file")).when(jsch).addIdentity("/file/that/does/not/exist", (String) null);102 send();103 }104 @Test(expectedExceptions = CitrusRuntimeException.class,expectedExceptionsMessageRegExp = ".*/notthere\\.key.*")105 public void withUnknownPrivateKey2() throws JSchException {106 strictHostChecking(false,null);107 client.getEndpointConfiguration().setPrivateKeyPath("classpath:com/consol/citrus/ssh/notthere.key");108 jsch.addIdentity("classpath:com/consol/citrus/ssh/notthere.key",(String) null);109 send();110 }111 @Test112 public void withPrivateKey() throws JSchException, IOException {113 strictHostChecking(false,null);114 client.getEndpointConfiguration().setPrivateKeyPath("classpath:com/consol/citrus/ssh/private.key");115 jsch.addIdentity(isA(String.class), (String) isNull());116 strictHostChecking(false, null);117 standardChannelPrepAndSend();118 }119 @Test120 public void withPassword() throws JSchException, IOException {121 client.getEndpointConfiguration().setPassword("consol");122 session.setUserInfo(getUserInfo("consol"));123 session.setPassword("consol");124 strictHostChecking(false, null);125 standardChannelPrepAndSend();126 }127 @Test128 public void straight() throws JSchException, IOException {129 strictHostChecking(false, null);130 standardChannelPrepAndSend();131 }132 private void send() {133 client.send(createMessage(COMMAND, STDIN), context);134 }135 private void disconnect() throws JSchException {136 channel.disconnect();137 when(session.isConnected()).thenReturn(true);138 session.disconnect();139 when(session.openChannel("exec")).thenReturn(channel);140 }141 private void prepareChannel(String pCommand, int pExitStatus) throws JSchException, IOException {142 channel.setErrStream((OutputStream) any());143 channel.setOutputStream((OutputStream) any());144 channel.setInputStream((InputStream) any());145 channel.setCommand(pCommand);146 channel.connect(CONNECTTION_TIMEOUT);147 when(channel.getOutputStream()).thenReturn(outStream);148 when(channel.isClosed()).thenReturn(false);149 when(channel.isClosed()).thenReturn(true);150 when(channel.getExitStatus()).thenReturn(pExitStatus);151 when(channel.isConnected()).thenReturn(true);152 }153 private Message createMessage(String pCommand, String pInput) {154 SshRequest request = new SshRequest(pCommand,pInput);155 StringResult payload = new StringResult();...

Full Screen

Full Screen

JSch

Using AI Code Generation

copy

Full Screen

1package com.consol.citrus.ssh.client;2import com.consol.citrus.dsl.testng.TestNGCitrusTestDesigner;3import org.springframework.beans.factory.annotation.Autowired;4import org.testng.annotations.Test;5public class SshClientTest extends TestNGCitrusTestDesigner {6 private SshClient sshClient;7 public void testSshClient() {8 variable("fileName", "newFile.txt");9 variable("fileContent", "This is a new file created by SSH client");10 sshClient.createFile("${fileName}", "${fileContent}");11 }12}

Full Screen

Full Screen

JSch

Using AI Code Generation

copy

Full Screen

1package com.consol.citrus.ssh.client;2import com.consol.citrus.testng.CitrusParameters;3import com.consol.citrus.annotations.CitrusTest;4import com.consol.citrus.dsl.testng.TestNGCitrusTestRunner;5import org.testng.annotations.Test;6public class SshClientTest extends TestNGCitrusTestRunner {7 @CitrusParameters("name")8 public void executeRemoteCommand() {9 variable("name", "Citrus");10 ssh()11 .client("sshClient")12 .command("echo Hello ${name}!")13 .validateCommandResult("Hello Citrus!");14 }15}16package com.consol.citrus.ssh.client;17import com.consol.citrus.dsl.builder.SshClientActionBuilder;18import com.consol.citrus.dsl.runner.TestRunner;19import com.consol.citrus.exceptions.CitrusRuntimeException;20import com.consol.citrus.testng.AbstractTestNGUnitTest;21import org.mockito.Mockito;22import org.testng.Assert;23import org.testng.annotations.Test;24import java.io.IOException;25import java.util.Collections;26import static org.mockito.Mockito.*;27public class SshClientTest extends AbstractTestNGUnitTest {28 private SshClient sshClient = new SshClient();29 public void testExecuteCommand() throws IOException {30 SshClientActionBuilder.SshCommand command = Mockito.mock(SshClientActionBuilder.SshCommand.class);31 SshClientActionBuilder.SshCommandResult commandResult = Mockito.mock(SshClientActionBuilder.SshCommandResult.class);32 when(command.execute(any(), any())).thenReturn(commandResult);33 when(commandResult.getCommandResult()).thenReturn("test");34 sshClient.setCommands(Collections.singletonList(command));35 SshClientActionBuilder.SshCommandResult result = sshClient.executeCommand("test", context);36 Assert.assertEquals(result.getCommandResult(), "test");37 verify(command).execute(any(), any());38 }39 @Test(expectedExceptions = CitrusRuntimeException.class)

Full Screen

Full Screen

JSch

Using AI Code Generation

copy

Full Screen

1package com.consol.citrus.ssh;2import com.consol.citrus.annotations.CitrusTest;3import com.consol.citrus.dsl.testng.TestNGCitrusTestRunner;4import com.consol.citrus.ssh.client.SshClient;5import com.consol.citrus.ssh.client.SshClientBuilder;6import org.springframework.beans.factory.annotation.Autowired;7import org.springframework.core.io.ClassPathResource;8import org.testng.annotations.Test;9public class SshJSchCopyFileIT extends TestNGCitrusTestRunner {10 private SshClient sshClient;11 public void testSshJSchCopyFile() {12 SshClientBuilder clientBuilder = new SshClientBuilder();13 clientBuilder.host("localhost");14 clientBuilder.port(22);15 clientBuilder.username("citrus");16 clientBuilder.password("citrus");17 SshClient client = clientBuilder.build();18 client.copyFile("remote-file.txt", "local-file.txt");19 }20}

Full Screen

Full Screen

JSch

Using AI Code Generation

copy

Full Screen

1package com.consol.citrus.ssh.client;2import com.consol.citrus.ssh.message.SshMessage;3import com.consol.citrus.ssh.message.SshMessageHeaders;4import com.consol.citrus.ssh.server.SshServer;5import com.consol.citrus.ssh.server.SshServerBuilder;6import com.consol.citrus.ssh.server.SshServerController;7import org.apache.sshd.common.NamedFactory;8import org.apache.sshd.common.session.Session;9import org.apache.sshd.server.Command;10import org.apache.sshd.server.Environment;11import org.apache.sshd.server.ExitCallback;12import org.apache.sshd.server.auth.password.PasswordAuthenticator;13import org.apache.sshd.server.command.ScpCommandFactory;14import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider;15import org.apache.sshd.server.session.ServerSession;16import org.apache.sshd.server.shell.ProcessShellFactory;17import org.apache.sshd.server.subsystem.sftp.SftpSubsystemFactory;18import org.slf4j.Logger;19import org.slf4j.LoggerFactory;20import org.springframework.context.annotation.Bean;21import org.springframework.context.annotation.Configuration;22import org.springframework.integration.annotation.IntegrationComponentScan;23import org.springframework.integration.annotation.MessagingGateway;24import org.springframework.integration.annotation.ServiceActivator;25import org.springframework.integration.config.EnableIntegration;26import org.springframework.integration.scheduling.PollerMetadata;27import org.springframework.integration.sftp.session.DefaultSftpSessionFactory;28import org.springframework.integration.sftp.session.SftpRemoteFileTemplate;29import org.springframework.messaging.Message;30import org.springframework.messaging.MessageHandler;31import org.springframework.messaging.MessagingException;32import org.springframework.messaging.support.MessageBuilder;33import org.springframework.scheduling.support.PeriodicTrigger;34import java.io.*;35import java.util.ArrayList;36import java.util.List;37import java.util.concurrent.TimeUnit;38public class SshClientTestConfig {39 private static final Logger LOG = LoggerFactory.getLogger(SshClientTestConfig.class);40 public SshServerController sshServerController() {41 return new SshServerController();42 }43 public SshServer sshServer() {

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful