本文整理汇总了Java中com.jcraft.jsch.Session类的典型用法代码示例。如果您正苦于以下问题:Java Session类的具体用法?Java Session怎么用?Java Session使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Session类属于com.jcraft.jsch包,在下文中一共展示了Session类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: fileFetch
import com.jcraft.jsch.Session; //导入依赖的package包/类
public static void fileFetch(String host, String user, String keyLocation, String sourceDir, String destDir) {
JSch jsch = new JSch();
Session session = null;
try {
// set up session
session = jsch.getSession(user,host);
// use private key instead of username/password
session.setConfig(
"PreferredAuthentications",
"publickey,gssapi-with-mic,keyboard-interactive,password");
jsch.addIdentity(keyLocation);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
// copy remote log file to localhost.
ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
channelSftp.connect();
channelSftp.get(sourceDir, destDir);
channelSftp.exit();
} catch (Exception e) {
e.printStackTrace();
} finally {
session.disconnect();
}
}
示例2: executeCommand
import com.jcraft.jsch.Session; //导入依赖的package包/类
/**
* Executes a given command. It opens exec channel for the command and closes
* the channel when it's done.
*
* @param session ssh connection to a remote server
* @param command command to execute
* @return command output string if the command succeeds, or null
*/
private static String executeCommand(Session session, String command) {
if (session == null || !session.isConnected()) {
return null;
}
log.trace("Execute command {} to {}", command, session.getHost());
try {
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
channel.setInputStream(null);
InputStream output = channel.getInputStream();
channel.connect();
String result = CharStreams.toString(new InputStreamReader(output));
channel.disconnect();
log.trace("Result of command {} on {}: {}", command, session.getHost(), result);
return result;
} catch (JSchException | IOException e) {
log.error("Failed to execute command {} on {} due to {}", command, session.getHost(), e.toString());
return null;
}
}
示例3: testTestCommand
import com.jcraft.jsch.Session; //导入依赖的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
示例4: executeCommand
import com.jcraft.jsch.Session; //导入依赖的package包/类
public void executeCommand(final String command) throws IOException { // Cliente SSH final
JSch jsch = new JSch();
Properties props = new Properties();
props.put("StrictHostKeyChecking", "no");
try {
Session session = jsch.getSession(user, host, 22);
session.setConfig(props);
session.setPassword(password);
session.connect();
java.util.logging.Logger.getLogger(RemoteShell.class.getName())
.log(Level.INFO, session.getServerVersion());
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
// Daqui para baixo é somente para imprimir a saida
channel.setInputStream(null);
((ChannelExec) channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
channel.connect();
byte[] tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0) {
break;
}
System.out.print(new String(tmp, 0, i));
}
if (channel.isClosed()) {
if (in.available() > 0) {
continue;
}
System.out
.println("exit-status: " + channel.getExitStatus());
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
}
}
channel.disconnect();
session.disconnect();
} catch (JSchException ex) {
java.util.logging.Logger.getLogger(RemoteShell.class.getName())
.log(Level.SEVERE, null, ex);
}
}
示例5: connectAndExecute
import com.jcraft.jsch.Session; //导入依赖的package包/类
public static String connectAndExecute(String user, String host, String password, String command1) {
String CommandOutput = null;
try {
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig(config);
session.connect();
// System.out.println("Connected");
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command1);
channel.setInputStream(null);
((ChannelExec) channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
channel.connect();
byte[] tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0)
break;
// System.out.print(new String(tmp, 0, i));
CommandOutput = new String(tmp, 0, i);
}
if (channel.isClosed()) {
// System.out.println("exit-status: " +
// channel.getExitStatus());
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
}
}
channel.disconnect();
session.disconnect();
// System.out.println("DONE");
} catch (Exception e) {
e.printStackTrace();
}
return CommandOutput;
}
示例6: init
import com.jcraft.jsch.Session; //导入依赖的package包/类
ChannelSftp init(String filename) throws JSchException, UnsupportedEncodingException {
jsch = new JSch();
ConnectionInfo ci = splitStringToConnectionInfo(filename);
Session session = jsch.getSession(ci.username, ci.host, ci.port);
UserInfo ui = new SftpUserInfo(ci.password);
session.setUserInfo(ui);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp c = (ChannelSftp) channel;
logDebug("success: init Sftp");
return c;
}
示例7: createSession
import com.jcraft.jsch.Session; //导入依赖的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;
}
示例8: establishWithKey
import com.jcraft.jsch.Session; //导入依赖的package包/类
public static Session establishWithKey(String sshHost, int sshPort, String user, String keyFilePath) throws JSchException {
File keyFile = new File(keyFilePath);
if (!keyFile.exists()) {
String errorMsg = "Could not find SSH public key file in path: " + keyFilePath;
logger.info(errorMsg);
throw new JSchException(errorMsg);
}
Session session;
JSch jsch = new JSch();
try {
jsch.addIdentity(keyFile.getAbsolutePath());
session = jsch.getSession(user, sshHost, sshPort);
}
catch (JSchException e) {
logger.error("SSH connection attempt to host: " + sshHost + ":" + sshPort + " failed");
throw e;
}
return connect(session, sshHost, sshPort);
}
示例9: testJschConnection
import com.jcraft.jsch.Session; //导入依赖的package包/类
@Test
public void testJschConnection() throws InterruptedException, SftpException, JSchException, IOException {
JSch jsch = new JSch();
String passphrase = "";
jsch.addIdentity(privateKey,
StringUtil.isEmpty(passphrase) ?
null : passphrase);
Session session = jsch.getSession(user, host, port);
System.out.println("session created.");
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
config.put("PreferredAuthentications",
"publickey,keyboard-interactive,password");
session.setConfig(config);
session.connect();
Thread.sleep(500);
session.disconnect();
}
示例10: pushToRepository
import com.jcraft.jsch.Session; //导入依赖的package包/类
/**
* Push all changes and tags to given remote.
*
* @param git
* instance.
* @param remote
* to be used.
* @param passphrase
* to access private key.
* @param privateKey
* file location.
*
* @return List of all results of given push.
*/
public Iterable<PushResult> pushToRepository(Git git, String remote, String passphrase, Path privateKey) {
SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
@Override
protected void configure(OpenSshConfig.Host host, Session session) {
session.setUserInfo(new PassphraseUserInfo(passphrase));
}
@Override
protected JSch createDefaultJSch(FS fs) throws JSchException {
if (privateKey != null) {
JSch defaultJSch = super.createDefaultJSch(fs);
defaultJSch.addIdentity(privateKey.toFile().getAbsolutePath());
return defaultJSch;
} else {
return super.createDefaultJSch(fs);
}
}
};
try {
return git.push()
.setRemote(remote)
.setPushAll()
.setPushTags()
.setTransportConfigCallback(transport -> {
SshTransport sshTransport = (SshTransport) transport;
sshTransport.setSshSessionFactory(sshSessionFactory);
})
.call();
} catch (GitAPIException e) {
throw new IllegalStateException(e);
}
}
示例11: close
import com.jcraft.jsch.Session; //导入依赖的package包/类
public synchronized void close() throws IOException {
if (closed) {
return;
}
super.close();
closed = true;
if (!channel.isConnected()) {
throw new IOException(E_CLIENT_NOTCONNECTED);
}
try {
Session session = channel.getSession();
channel.disconnect();
session.disconnect();
} catch (JSchException e) {
throw new IOException(StringUtils.stringifyException(e));
}
}
示例12: keepSessionConnected
import com.jcraft.jsch.Session; //导入依赖的package包/类
private synchronized void keepSessionConnected(Channel channel){
try {
Session session = channel.getSession();
boolean contains = false;
for(Entry<Session, Integer> e2 : usedSessions.entrySet()){
if (e2.getKey() == session) {
contains = true;
break;
}
}
if(contains){
usedSessions.put(session,usedSessions.get(session)+1);
}
else {
usedSessions.put(session, 1);
}
} catch (JSchException e) {
e.printStackTrace();
}
}
示例13: releaseSession
import com.jcraft.jsch.Session; //导入依赖的package包/类
public synchronized void releaseSession(Channel channel) {
try {
Session session = channel.getSession();
boolean contains = false;
for(Entry<Session, Integer> e2 : usedSessions.entrySet()){
if (e2.getKey() == session) {
contains = true;
break;
}
}
if(contains){
if(usedSessions.get(session)<=1){
usedSessions.remove(session);
if(!sessions.values().contains(session))
channel.getSession().disconnect();
}
else{
usedSessions.put(session, usedSessions.get(session) - 1);
}
}
} catch (JSchException e) {
e.printStackTrace();
}
}
示例14: removeSession
import com.jcraft.jsch.Session; //导入依赖的package包/类
public synchronized void removeSession(Uri cred){
for(Entry<Credential, Session> e : sessions.entrySet()){
Uri uri = Uri.parse(e.getKey().getUriString());
if(uri.getHost().equals(cred.getHost())&&uri.getPort()==cred.getPort()){
boolean doNotDisconnect = false;
for(Entry<Session, Integer> e2 : usedSessions.entrySet()){
if (e2.getKey() == e.getValue()) {
doNotDisconnect = true;
break;
}
}
if(!doNotDisconnect) {
e.getValue().disconnect();
}
sessions.remove(e.getKey());
}
}
}
示例15: create
import com.jcraft.jsch.Session; //导入依赖的package包/类
@Override
public Session create(ConnectionDetails connectionDetails) throws Exception {
log.debug("Creating session for "+connectionDetails);
Session session = null;
try {
byte[] privateKey = connectionDetails.getPrivateKey();
if (privateKey != null) {
jsch.addIdentity(connectionDetails.getUsername(), privateKey, null, connectionDetails.getPassword().getBytes());
}
session = jsch.getSession(connectionDetails.getUsername(), connectionDetails.getHost(), connectionDetails.getPort());
session.setPassword(connectionDetails.getPassword());
if (!hostKeyValidation) {
session.setConfig("StrictHostKeyChecking", "no");
}
session.setDaemonThread(true);
session.connect();
} catch (Exception e) {
log.error("Failed to connect to "+connectionDetails);
throw e;
}
return session;
}