本文整理匯總了Java中com.jcraft.jsch.JSch類的典型用法代碼示例。如果您正苦於以下問題:Java JSch類的具體用法?Java JSch怎麽用?Java JSch使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
JSch類屬於com.jcraft.jsch包,在下文中一共展示了JSch類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: upload
import com.jcraft.jsch.JSch; //導入依賴的package包/類
private void upload(String filename) {
try {
JSch jsch = new JSch();
Session session = jsch.getSession(login, server, port);
session.setPassword(password);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp channelSftp = (ChannelSftp) channel;
channelSftp.cd(workingDirectory);
File f = new File(filename);
channelSftp.put(new FileInputStream(f), f.getName());
f.delete();
} catch (Exception ex) {
ex.printStackTrace();
}
}
示例2: fileFetch
import com.jcraft.jsch.JSch; //導入依賴的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();
}
}
示例3: build
import com.jcraft.jsch.JSch; //導入依賴的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;
}
示例4: listFiles
import com.jcraft.jsch.JSch; //導入依賴的package包/類
/**
* Lists directory files on remote server.
* @throws URISyntaxException
* @throws JSchException
* @throws SftpException
*/
private void listFiles() throws URISyntaxException, JSchException, SftpException {
JSch jsch = new JSch();
JSch.setLogger(new JschLogger());
setupSftpIdentity(jsch);
URI uri = new URI(sftpUrl);
Session session = jsch.getSession(sshLogin, uri.getHost(), 22);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
System.out.println("Connected to SFTP server");
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
Vector<LsEntry> directoryEntries = sftpChannel.ls(uri.getPath());
for (LsEntry file : directoryEntries) {
System.out.println(String.format("File - %s", file.getFilename()));
}
sftpChannel.exit();
session.disconnect();
}
示例5: connect
import com.jcraft.jsch.JSch; //導入依賴的package包/類
/**
* Connect to a remote host and return a channel (session and jsch are set)
*/
Channel connect(String channleType, String sshCommand) throws Exception {
JSch.setConfig("StrictHostKeyChecking", "no"); // Not recommended, but useful
jsch = new JSch();
// Some "reasonable" defaults
if (Gpr.exists(defaultKnownHosts)) jsch.setKnownHosts(defaultKnownHosts);
for (String identity : defaultKnownIdentity)
if (Gpr.exists(identity)) jsch.addIdentity(identity);
// Create session and connect
if (debug) Gpr.debug("Create conection:\n\tuser: '" + host.getUserName() + "'\n\thost : '" + host.getHostName() + "'\n\tport : " + host.getPort());
session = jsch.getSession(host.getUserName(), host.getHostName(), host.getPort());
session.setUserInfo(new SshUserInfo());
session.connect();
// Create channel
channel = session.openChannel(channleType);
if ((sshCommand != null) && (channel instanceof ChannelExec)) ((ChannelExec) channel).setCommand(sshCommand);
return channel;
}
示例6: init
import com.jcraft.jsch.JSch; //導入依賴的package包/類
public SftpClient init() {
try {
String host = PropertiesUtil.getString("sftp.host");
int port = PropertiesUtil.getInt("sftp.port");
String userName = PropertiesUtil.getString("sftp.user.name");
String password = PropertiesUtil.getString("sftp.user.password");
Integer timeout = PropertiesUtil.getInt("sftp.timeout");
Integer aliveMax = PropertiesUtil.getInt("sftp.aliveMax");
JSch jsch = new JSch(); // 創建JSch對象
session = jsch.getSession(userName, host, port); // 根據用戶名,主機ip,端口獲取一個Session對象
if (password != null) {
session.setPassword(password); // 設置密碼
}
session.setConfig("StrictHostKeyChecking", "no"); // 為Session對象設置properties
if (timeout != null) session.setTimeout(timeout); // 設置timeout時間
if (aliveMax != null) session.setServerAliveCountMax(aliveMax);
session.connect(); // 通過Session建立鏈接
channel = (ChannelSftp)session.openChannel("sftp"); // 打開SFTP通道
channel.connect(); // 建立SFTP通道的連接
logger.info("SSH Channel connected.");
} catch (JSchException e) {
throw new FtpException("", e);
}
return this;
}
示例7: testTestCommand
import com.jcraft.jsch.JSch; //導入依賴的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
示例8: executeCommand
import com.jcraft.jsch.JSch; //導入依賴的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);
}
}
示例9: connectWithIdentity
import com.jcraft.jsch.JSch; //導入依賴的package包/類
public void connectWithIdentity(String identityPath, String passPhrase) throws JSchException,FileNotFoundException {
if (identityPath == null || new File(identityPath).exists() == false) {
throw new FileNotFoundException("Identity file not found !") ;
}
if (m_session != null) {
m_session.disconnect();
}
preConnect();
JSch jsch = new JSch();
if (passPhrase != null && passPhrase.length() >0) {
jsch.addIdentity(identityPath, passPhrase);
}
else {
jsch.addIdentity(identityPath);
}
SSH2User userInfo = new SSH2User(m_username, passPhrase);
m_session = jsch.getSession(m_username, m_host, m_port);
m_session.setConfig(infos);
m_session.setUserInfo(userInfo);
m_session.connect();
}
示例10: SSHShell
import com.jcraft.jsch.JSch; //導入依賴的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();
}
示例11: generateSSHKeys
import com.jcraft.jsch.JSch; //導入依賴的package包/類
/**
* Automatically generate SSH keys.
* @param passPhrase the byte array content to be uploaded
* @param comment the name of the file for which the content will be saved into
* @return SSH public and private key
* @throws Exception exception thrown
*/
public static SshPublicPrivateKey generateSSHKeys(String passPhrase, String comment) throws Exception {
JSch jsch = new JSch();
KeyPair keyPair = KeyPair.genKeyPair(jsch, KeyPair.RSA);
ByteArrayOutputStream privateKeyBuff = new ByteArrayOutputStream(2048);
ByteArrayOutputStream publicKeyBuff = new ByteArrayOutputStream(2048);
keyPair.writePublicKey(publicKeyBuff, (comment != null) ? comment : "SSHCerts");
if (passPhrase == null || passPhrase.isEmpty()) {
keyPair.writePrivateKey(privateKeyBuff);
} else {
keyPair.writePrivateKey(privateKeyBuff, passPhrase.getBytes());
}
return new SshPublicPrivateKey(privateKeyBuff.toString(), publicKeyBuff.toString());
}
示例12: connectAndExecute
import com.jcraft.jsch.JSch; //導入依賴的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;
}
示例13: init
import com.jcraft.jsch.JSch; //導入依賴的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;
}
示例14: createSession
import com.jcraft.jsch.JSch; //導入依賴的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;
}
示例15: establishWithKey
import com.jcraft.jsch.JSch; //導入依賴的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);
}