本文整理汇总了Java中com.jcraft.jsch.JSchException类的典型用法代码示例。如果您正苦于以下问题:Java JSchException类的具体用法?Java JSchException怎么用?Java JSchException使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
JSchException类属于com.jcraft.jsch包,在下文中一共展示了JSchException类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: build
import com.jcraft.jsch.JSchException; //导入依赖的package包/类
public JSch build() throws JSchException {
LOGGER.debug("Initializing JSch Logger");
JSch.setLogger(new JschLogger());
final JSch jsch = new JSch();
try {
if (null != knownHostsFileName && new File(knownHostsFileName).exists()) {
jsch.setKnownHosts(knownHostsFileName);
}
if (null != privateKeyFileName && new File(privateKeyFileName).exists()) {
jsch.addIdentity(privateKeyFileName);
}
} catch (JSchException e) {
LOGGER.error("Could not access known hosts or private key file.", e);
if (!(e.getCause() instanceof FileNotFoundException)) {
throw new JSchException();
}
}
return jsch;
}
示例2: testTestCommand
import com.jcraft.jsch.JSchException; //导入依赖的package包/类
@Test
public void testTestCommand() throws JSchException, IOException {
JSch jsch = new JSch();
Session session = jsch.getSession("admin", "localhost", properties.getShell().getPort());
jsch.addIdentity("src/test/resources/id_rsa");
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
ChannelShell channel = (ChannelShell) session.openChannel("shell");
PipedInputStream pis = new PipedInputStream();
PipedOutputStream pos = new PipedOutputStream();
channel.setInputStream(new PipedInputStream(pos));
channel.setOutputStream(new PipedOutputStream(pis));
channel.connect();
pos.write("test run bob\r".getBytes(StandardCharsets.UTF_8));
pos.flush();
verifyResponse(pis, "test run bob");
pis.close();
pos.close();
channel.disconnect();
session.disconnect();
}
开发者ID:anand1st,项目名称:sshd-shell-spring-boot,代码行数:24,代码来源:SshdShellAutoConfigurationWithPublicKeyAndBannerImageTest.java
示例3: SSHShell
import com.jcraft.jsch.JSchException; //导入依赖的package包/类
/**
* Creates SSHShell.
*
* @param host the host name
* @param port the ssh port
* @param userName the ssh user name
* @param sshPrivateKey the ssh password
* @return the shell
* @throws JSchException
* @throws IOException
*/
private SSHShell(String host, int port, String userName, byte[] sshPrivateKey)
throws JSchException, IOException {
Closure expectClosure = getExpectClosure();
for (String linuxPromptPattern : new String[]{"\\>", "#", "~#", "~\\$"}) {
try {
Match match = new RegExpMatch(linuxPromptPattern, expectClosure);
linuxPromptMatches.add(match);
} catch (MalformedPatternException malformedEx) {
throw new RuntimeException(malformedEx);
}
}
JSch jsch = new JSch();
jsch.setKnownHosts(System.getProperty("user.home") + "/.ssh/known_hosts");
jsch.addIdentity(host, sshPrivateKey, (byte[]) null, (byte[]) null);
this.session = jsch.getSession(userName, host, port);
this.session.setConfig("StrictHostKeyChecking", "no");
this.session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
session.connect(60000);
this.channel = (ChannelShell) session.openChannel("shell");
this.expect = new Expect4j(channel.getInputStream(), channel.getOutputStream());
channel.connect();
}
示例4: work
import com.jcraft.jsch.JSchException; //导入依赖的package包/类
protected void work() throws IOException, CancellationException, JSchException, SftpException, ExecutionException, InterruptedException {
if (LOG.isLoggable(Level.FINE)) {
LOG.log(Level.FINE, "{0} started", getTraceName());
}
ChannelSftp cftp = getChannel();
RemoteStatistics.ActivityID activityID = RemoteStatistics.startChannelActivity("download", srcFileName); // NOI18N
try {
cftp.get(srcFileName, dstFileName);
} catch (SftpException e) {
if (MiscUtils.mightBrokeSftpChannel(e)) {
cftp.quit();
}
throw decorateSftpException(e, srcFileName);
} finally {
releaseChannel(cftp);
RemoteStatistics.stopChannelActivity(activityID, new File(dstFileName).length());
}
}
示例5: createSession
import com.jcraft.jsch.JSchException; //导入依赖的package包/类
private Session createSession(String host, Args args) throws JSchException {
JSch jsch = new JSch();
for (String keyFile : getKeyFiles()) {
jsch.addIdentity(keyFile);
}
JSch.setLogger(new LogAdapter());
Session session = jsch.getSession(args.user, host, args.sshPort);
session.setConfig("StrictHostKeyChecking", "no");
return session;
}
示例6: get
import com.jcraft.jsch.JSchException; //导入依赖的package包/类
@Override
public SessionFactory get() {
if (sessionFactory == null) {
try {
synchronized (this) {
System.setProperty(DefaultSessionFactory.PROPERTY_JSCH_KNOWN_HOSTS_FILE, knownHosts);
sessionFactory = new DefaultSessionFactory();
sessionFactory.setPort(sshPort);
LOG.debug("Session factory created for {}@{}:{}", sessionFactory.getUsername(), sessionFactory.getHostname(),
sessionFactory.getPort());
}
sessionFactory.setIdentitiesFromPrivateKeys(identityKeys);
} catch (JSchException | RuntimeException e) {
throw new WaggleDanceException(
"Unable to create factory with knownHosts=" + knownHosts + " and identityKeys=" + identityKeys, e);
}
}
return sessionFactory;
}
示例7: setupJSchIdentityRepository
import com.jcraft.jsch.JSchException; //导入依赖的package包/类
private boolean setupJSchIdentityRepository (JSch jsch, String identityFile, boolean preferAgent) throws JSchException {
boolean agentUsed = false;
if (preferAgent) {
Connector con = ConnectorFactory.getInstance().createConnector(ConnectorFactory.ConnectorKind.ANY);
if (con != null) {
IdentityRepository irepo = new IdentityRepositoryImpl(con);
if (irepo.getStatus() == IdentityRepository.RUNNING) {
jsch.setIdentityRepository(irepo);
agentUsed = true;
}
}
}
if (!agentUsed) {
jsch.setIdentityRepository(null);
// remove all identity files
jsch.removeAllIdentity();
// and add the one specified by CredentialsProvider
jsch.addIdentity(identityFile);
}
return agentUsed;
}
示例8: call
import com.jcraft.jsch.JSchException; //导入依赖的package包/类
@Override
public ExecResults call() throws Exception {
int rc;
List<String> error = new LinkedList<>();
try {
channel.connect();
channel.get(remoteLoc, file.getAbsolutePath());
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Completed downloading [" + file.getAbsolutePath() + "] to [" + remoteLoc + "]");
}
} catch (JSchException | SftpException e) {
String msg = "Encountered problems when downloading [" + remoteLoc + "]. Root cause : " + e.getMessage();
error.add(msg);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Failed downloading [" + file.getAbsolutePath() + "] to [" + remoteLoc + "]", e);
}
} finally {
rc = channel.getExitStatus();
channel.disconnect();
}
return new ExecResults(new LinkedList<>(), error, rc);
}
示例9: isValidSSHKeyFile
import com.jcraft.jsch.JSchException; //导入依赖的package包/类
public static boolean isValidSSHKeyFile(String filename) {
JSch test = new JSch();
try {
test.addIdentity(filename);
} catch (JSchException ex) {
return false;
}
return true;
}
示例10: openSession
import com.jcraft.jsch.JSchException; //导入依赖的package包/类
protected Session openSession(final ProcessContext context) throws JSchException {
final JSch jsch = new JSch();
final String hostKeyVal = context.getProperty(HOST_KEY_FILE).getValue();
if (hostKeyVal != null) {
jsch.setKnownHosts(hostKeyVal);
}
final Session session = jsch.getSession(context.getProperty(USERNAME).evaluateAttributeExpressions().getValue(),
context.getProperty(HOSTNAME).evaluateAttributeExpressions().getValue(),
context.getProperty(PORT).evaluateAttributeExpressions().asInteger().intValue());
final Properties properties = new Properties();
properties.setProperty("StrictHostKeyChecking", context.getProperty(STRICT_HOST_KEY_CHECKING).asBoolean() ? "yes" : "no");
properties.setProperty("PreferredAuthentications", "publickey,password,keyboard-interactive");
final PropertyValue compressionValue = context.getProperty(USE_COMPRESSION);
if (compressionValue != null && "true".equalsIgnoreCase(compressionValue.getValue())) {
properties.setProperty("compression.s2c", "[email protected],zlib,none");
properties.setProperty("compression.c2s", "[email protected],zlib,none");
} else {
properties.setProperty("compression.s2c", "none");
properties.setProperty("compression.c2s", "none");
}
session.setConfig(properties);
final String privateKeyFile = context.getProperty(PRIVATE_KEY_PATH).evaluateAttributeExpressions().getValue();
if (privateKeyFile != null) {
jsch.addIdentity(privateKeyFile, context.getProperty(PRIVATE_KEY_PASSPHRASE).evaluateAttributeExpressions().getValue());
}
final String password = context.getProperty(PASSWORD).evaluateAttributeExpressions().getValue();
if (password != null) {
session.setPassword(password);
}
session.setTimeout(context.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
session.connect();
return session;
}
示例11: call
import com.jcraft.jsch.JSchException; //导入依赖的package包/类
@Override
public ExecResults call() throws Exception {
int rc;
List<String> error = new LinkedList<>();
try (InputStream stream = new FileInputStream(file)) {
channel.connect();
channel.put(stream, remoteLoc + "/" + file.getName());
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Completed uploading [" + file.getAbsolutePath() + "] to [" + remoteLoc + "]");
}
} catch (JSchException | SftpException e) {
String msg = "Encountered problems when uploading [" + remoteLoc + "]. Root cause : " + e.getMessage();
error.add(msg);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Failed uploading [" + file.getAbsolutePath() + "] to [" + remoteLoc + "]", e);
}
} finally {
rc = channel.getExitStatus();
channel.disconnect();
}
return new ExecResults(new LinkedList<>(), error, rc);
}
示例12: connect
import com.jcraft.jsch.JSchException; //导入依赖的package包/类
public static Session connect(String host, Integer port, String user, String password) throws JSchException{
Session session = null;
try {
JSch jsch = new JSch();
if(port != null){
session = jsch.getSession(user, host, port.intValue());
}else{
session = jsch.getSession(user, host);
}
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
//time out
session.connect(3000);
} catch (JSchException e) {
e.printStackTrace();
System.out.println("SFTPUitl connection error");
throw e;
}
return session;
}
示例13: initSessionFactory
import com.jcraft.jsch.JSchException; //导入依赖的package包/类
private void initSessionFactory() {
JschConfigSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
@Override
protected void configure(Host host, Session session) {
session.setConfig("StrictHostKeyChecking", "no");
}
@Override
protected JSch createDefaultJSch(FS fs) throws JSchException {
JSch jSch = super.createDefaultJSch(fs);
// apply customized private key
if (privateKeyPath != null) {
jSch.removeAllIdentity();
jSch.addIdentity(privateKeyPath.toString());
}
return jSch;
}
};
transportConfigCallback = transport -> {
SshTransport sshTransport = (SshTransport) transport;
sshTransport.setSshSessionFactory(sshSessionFactory);
};
}
示例14: createTCPProxy
import com.jcraft.jsch.JSchException; //导入依赖的package包/类
private void createTCPProxy() {
try {
final String cleanCommand = String.format("sudo docker ps -a | grep 'hours ago' | awk '{print $1}' | xargs --no-run-if-empty sudo docker rm",
containerName,
this.targetHost,
this.targetPort,
sourceIPs,
ImageRegistry.get().tcpProxy());
LOGGER.info("Establishing SSH shell");
ssh = SshUtil.getInstance()
.createSshSession(TestConfiguration.proxyHostUsername(), getProxyHost());
ssh.connect();
LOGGER.debug("Connected to ssh console");
final ChannelExec cleanChannel = (ChannelExec) ssh.openChannel("exec");
cleanChannel.setPty(true);
cleanChannel.setCommand(cleanCommand);
cleanChannel.setInputStream(null);
cleanChannel.setOutputStream(System.err);
LOGGER.debug("Executing command: '{}'", cleanCommand);
cleanChannel.connect();
cleanChannel.disconnect();
final String command = String.format("sudo docker run -it --name %s --net=host --rm -e AB_OFF=true -e TARGET_HOST=%s -e TARGET_PORT=%s -e TARGET_VIA=%s %s",
containerName,
this.targetHost,
this.targetPort,
sourceIPs,
ImageRegistry.get().tcpProxy());
LOGGER.info("Establishing SSH shell");
ssh = SshUtil.getInstance()
.createSshSession(TestConfiguration.proxyHostUsername(), getProxyHost());
ssh.connect();
LOGGER.debug("Connected to ssh console");
final ChannelExec channel = (ChannelExec) ssh.openChannel("exec");
channel.setPty(true);
channel.setCommand(command);
channel.setInputStream(null);
channel.setOutputStream(System.err);
LOGGER.debug("Executing command: '{}'", command);
channel.connect();
final LineIterator li = IOUtils.lineIterator(new InputStreamReader(channel.getInputStream()));
final Pattern portLine = Pattern.compile(".*Listening on port ([0-9]*).*$");
listenPort = 0;
while (li.hasNext()) {
final String line = li.next();
LOGGER.trace("Shell line: {}", line);
final Matcher m = portLine.matcher(line);
if (m.matches()) {
listenPort = Integer.parseInt(m.group(1));
LOGGER.info("Connection listening on port {}", listenPort);
break;
}
}
channel.disconnect();
} catch (final JSchException | IOException e) {
LOGGER.debug("Error in creating SSH connection to proxy host", e);
throw new IllegalStateException("Cannot open SSH connection", e);
}
}
示例15: helpCreateStart
import com.jcraft.jsch.JSchException; //导入依赖的package包/类
/**
* Orchestrates ZIP upload and sends commands through SSH.
* Depending on the artifact type the method will use create or start scripts.
*
* @param type The artifact type which determines the nature of the method
*/
private void helpCreateStart(ArtifactType type) throws JSchException {
for(ArrayList<Node> currentBranch : allBranches){
MachineNode mNode = (MachineNode) currentBranch.get(0);
makeSSHConnection(mNode);
if (type == ArtifactType.CREATE){
ssh.uploadAndUnzipZip(zip);
}
for(int i=1; i<currentBranch.size();i++){
ServiceNode currentNode = (ServiceNode) currentBranch.get(i);
ArtifactPath createPath = currentNode.getImplementationArtifact(ArtifactType.CREATE);
ArtifactPath startPath = currentNode.getImplementationArtifact(ArtifactType.START);
if(type==ArtifactType.CREATE){
executeScript(createPath);
executeScript(startPath);
} else {
executeScript(startPath);
}
}
ssh.close();
}
}