本文整理汇总了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);
}