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

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

Source:SshClient.java Github

copy

Full Screen

...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());...

Full Screen

Full Screen

Source:SshClientTest.java Github

copy

Full Screen

...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();156 new SshMarshaller().marshal(request, payload);157 return new DefaultMessage(payload.toString());158 }159 private void strictHostChecking(boolean flag,String knownHosts) {160 if (flag) {161 client.getEndpointConfiguration().setStrictHostChecking(true);162 session.setConfig(KnownHostsServerKeyVerifier.STRICT_CHECKING_OPTION,"yes");163 client.getEndpointConfiguration().setKnownHosts(knownHosts);164 } else {165 session.setConfig(KnownHostsServerKeyVerifier.STRICT_CHECKING_OPTION,"no");166 }167 }168 private UserInfo getUserInfo(final String arg) {169 argThat(new ArgumentMatcher() {170 public boolean matches(Object argument) {171 UserInfo info = (UserInfo) argument;172 assertFalse(info.promptPassphrase("bla"));173 assertFalse(info.promptYesNo("bla"));174 assertFalse(info.promptPassword("bla"));175 assertNull(info.getPassphrase());176 return info.getPassword().equals(arg);177 }...

Full Screen

Full Screen

Source:SshClientBuilder.java Github

copy

Full Screen

...96 * @param knownHosts97 * @return98 */99 public SshClientBuilder knownHosts(String knownHosts) {100 endpoint.getEndpointConfiguration().setKnownHosts(knownHosts);101 return this;102 }103 /**104 * Sets the commandTimeout property.105 * @param commandTimeout106 * @return107 */108 public SshClientBuilder commandTimeout(long commandTimeout) {109 endpoint.getEndpointConfiguration().setCommandTimeout(commandTimeout);110 return this;111 }112 /**113 * Sets the connectionTimeout property.114 * @param connectionTimeout...

Full Screen

Full Screen

setKnownHosts

Using AI Code Generation

copy

Full Screen

1package com.consol.citrus.ssh.client;2import com.consol.citrus.annotations.CitrusTest;3import com.consol.citrus.dsl.testng.TestNGCitrusTestRunner;4import org.testng.annotations.Test;5public class setKnownHostsJavaIT extends TestNGCitrusTestRunner {6 public void setKnownHostsJavaIT() {7 variable("host", "localhost");8 variable("port", "22");9 variable("user", "user");10 variable("password", "password");11 ssh()12 .client("sshClient")13 .command("ls -la")14 .send()15 .receive("total");16 ssh()17 .client("sshClient")18 .command("ls -la")19 .send()20 .receive("total");21 ssh()22 .client("sshClient")23 .command("ls -la")24 .send()25 .receive("total");26 }27}28org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'setKnownHostsJavaIT' defined in file [/Users/.../setKnownHostsJavaIT.java]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sshClient' defined in com.consol.citrus.dsl.runner.TestRunner: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Host key verification failed for localhost:2229 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:575)30 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498)31 at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)32 at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)33 at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)34 at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)35 at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:843)36 at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877)

Full Screen

Full Screen

setKnownHosts

Using AI Code Generation

copy

Full Screen

1package com.consol.citrus.ssh.client;2import com.consol.citrus.ssh.client.SshClient;3import com.consol.citrus.ssh.client.SshClientBuilder;4import org.testng.annotations.Test;5import java.io.File;6import java.util.ArrayList;7import java.util.List;8public class SshClientTest {9public void testSshClient() {10SshClientBuilder sshClientBuilder = new SshClientBuilder();11SshClient sshClient = sshClientBuilder.build();12List<File> files = new ArrayList<File>();13files.add(new File("C:\\Users\\user\\Desktop\\known_hosts"));14sshClient.setKnownHosts(files);15}16}17package com.consol.citrus.ssh.client;18import com.consol.citrus.ssh.client.SshClient;19import com.consol.citrus.ssh.client.SshClientBuilder;20import org.testng.annotations.Test;21public class SshClientTest {22public void testSshClient() {23SshClientBuilder sshClientBuilder = new SshClientBuilder();24SshClient sshClient = sshClientBuilder.build();25sshClient.setPort(22);26}27}28package com.consol.citrus.ssh.client;29import com.consol.citrus.ssh.client.SshClient;30import com.consol.citrus.ssh.client.SshClientBuilder;31import org.testng.annotations.Test;32import java.io.File;33public class SshClientTest {34public void testSshClient() {35SshClientBuilder sshClientBuilder = new SshClientBuilder();36SshClient sshClient = sshClientBuilder.build();37sshClient.setPrivateKey(new File("C:\\Users\\user\\Desktop\\private_key"));38}39}40package com.consol.citrus.ssh.client;41import com.consol.citrus.ssh.client.SshClient;42import com.consol.citrus.ssh.client.SshClientBuilder;43import org.testng.annotations.Test;44public class SshClientTest {45public void testSshClient() {

Full Screen

Full Screen

setKnownHosts

Using AI Code Generation

copy

Full Screen

1import org.springframework.context.annotation.Bean;2import org.springframework.context.annotation.Configuration;3import org.springframework.context.annotation.Import;4import com.consol.citrus.dsl.builder.TestBuilder;5import com.consol.citrus.dsl.endpoint.CitrusEndpoints;6import com.consol.citrus.dsl.runner.TestRunner;7import com.consol.citrus.ssh.client.SshClient;8import com.consol.citrus.ssh.message.SshMessage;9import com.consol.citrus.ssh.server.SshServer;10import com.consol.citrus.ssh.server.SshServerBuilder;11@Import({SshServer.class, SshClient.class})12public class 3 {13 public TestRunner sshServer() {14 return CitrusEndpoints.ssh()15 .server()16 .autoStart(true)17 .port(2222)18 .user("user")19 .password("password")20 .build();21 }22 public TestRunner sshClient() {23 return CitrusEndpoints.ssh()24 .client()25 .autoStart(true)26 .port(2222)27 .knownHosts("localhost")28 .build();29 }30 public TestBuilder sshTest() {31 return new TestBuilder() {32 public void configure() {33 ssh(sshClient())34 .send("ls -al")35 .receive("drwxr-xr-x 2 user user 4096 Jul 26 15:17 .")36 .receive("drwxr-xr-x 3 user user 4096 Jul 26 15:17 ..")37 .receive("total 8")38 .receive("drwxr-xr-x 2 user user 4096 Jul 26 15:17 .")39 .receive("drwxr-xr-x 3 user user 4096 Jul 26 15:17 ..")40 .receive("total 8")41 .receive("drwxr-xr-x 2 user user 4096 Jul 26 15:17 .")42 .receive("drwxr-xr-x 3 user user 4096 Jul 26 15:17 ..")43 .receive("total 8")44 .receive("drwxr-xr-x 2 user user 4096 Jul 26 15:17 .")

Full Screen

Full Screen

setKnownHosts

Using AI Code Generation

copy

Full Screen

1package com.consol.citrus.ssh.client;2import com.consol.citrus.context.TestContext;3import com.consol.citrus.testng.AbstractTestNGUnitTest;4import org.mockito.Mockito;5import org.springframework.core.io.ClassPathResource;6import org.testng.Assert;7import org.testng.annotations.Test;8public class SshClientTest extends AbstractTestNGUnitTest {9 private SshClient sshClient = new SshClient();10 public void testSetKnownHosts() {11 sshClient.setKnownHosts(new ClassPathResource("known_hosts"));12 Assert.assertEquals(sshClient.getKnownHosts().getFile().getName(), "known_hosts");13 }14}15package com.consol.citrus.ssh.client;16import com.consol.citrus.context.TestContext;17import com.consol.citrus.testng.AbstractTestNGUnitTest;18import org.mockito.Mockito;19import org.springframework.core.io.ClassPathResource;20import org.testng.Assert;21import org.testng.annotations.Test;22public class SshClientTest extends AbstractTestNGUnitTest {23 private SshClient sshClient = new SshClient();24 public void testSetKnownHosts() {25 sshClient.setKnownHosts(new ClassPathResource("known_hosts"));26 Assert.assertEquals(sshClient.getKnownHosts().getFile().getName(), "known_hosts");27 }28}29package com.consol.citrus.ssh.client;30import com.consol.citrus.context.TestContext;31import com.consol.citrus.testng.AbstractTestNGUnitTest;32import org.mockito.Mockito;33import org.springframework.core.io.ClassPathResource;34import org.testng.Assert;35import org.testng.annotations.Test;36public class SshClientTest extends AbstractTestNGUnitTest {37 private SshClient sshClient = new SshClient();38 public void testSetKnownHosts() {39 sshClient.setKnownHosts(new ClassPathResource("known_hosts"));40 Assert.assertEquals(sshClient.getKnownHosts().getFile().getName(), "known_hosts");41 }42}

Full Screen

Full Screen

setKnownHosts

Using AI Code Generation

copy

Full Screen

1sshClient.setKnownHosts("/home/user/.ssh/known_hosts");2sshClient.setAllowUnknownHosts(true);3sshClient.setStrictHostKeyChecking(true);4sshClient.setStrictHostKeyChecking(false);5sshClient.setStrictHostKeyChecking("no");6sshClient.setStrictHostKeyChecking("yes");7sshClient.setStrictHostKeyChecking("ask");8sshClient.setStrictHostKeyChecking("accept-new");

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