Skip to content

Instantly share code, notes, and snippets.

@Kamabye Kamabye/AES.java forked from ymnk/AES.java
Created Apr 17, 2014

Embed
What would you like to do?
README of example directory
====================================================================
Last modified: Wed Oct 16 13:53:12 UTC 2002
This directory contains some examples, which demonstrate how to use JSch
- Shell.java
This program enables you to connect to sshd server and get the shell prompt.
$ CLASSPATH=.:../build javac Shell.java
$ CLASSPATH=.:../build java Shell
You will be asked username, hostname and passwd.
If everything works fine, you will get the shell prompt. Output will
be ugly because of lacks of terminal-emulation, but you can issue commands.
- X11Forwarding.java
This program will demonstrate X11 forwarding.
$ CLASSPATH=.:../build javac X11Forwarding.java
$ CLASSPATH=.:../build java X11Forwarding
You will be asked username, hostname, displayname and passwd.
If your X server does not run at 127.0.0.1, please enter correct
displayname. If everything works fine, you will get the shell prompt.
Try X applications; for example, xlogo.
- Exec.java
This program will demonstrate remote exec.
$ CLASSPATH=.:../build javac Exec.java
$ CLASSPATH=.:../build java Exec
You will be asked username, hostname, displayname, passwd and command.
If everything works fine, given command will be invoked
on the remote side and outputs will be printed out.
- ViaHTTP.java
This program will demonstrate the ssh session via HTTP proxy.
$ CLASSPATH=.:../build javac ViaHTTP.java
$ CLASSPATH=.:../build java ViaHTTP
You will be asked username, hostname, proxy-server and passwd.
If everything works fine, you will get the shell prompt.
- ViaSOCKS.java
This program will demonstrate the ssh session via SOCKS proxy.
$ CLASSPATH=.:../build javac ViaSOCKS.java
$ CLASSPATH=.:../build java ViaSOCKS
You will be asked username, hostname, proxy-server and passwd.
If everything works fine, you will get the shell prompt.
- PortForwardingR.java
This program will demonstrate the port forwarding like option -R of
ssh command; the given port on the remote host will be forwarded to
the given host and port on the local side.
$ CLASSPATH=.:../build javac PortForwardingR.java
$ CLASSPATH=.:../build java PortForwardingR
You will be asked username, hostname, port:host:hostport and passwd.
If everything works fine, you will get the shell prompt.
Try the port on remote host.
- PortForwardingL.java
This program will demonstrate the port forwarding like option -L of
ssh command; the given port on the local host will be forwarded to
the given remote host and port on the remote side.
$ CLASSPATH=.:../build javac PortForwardingL.java
$ CLASSPATH=.:../build java PortForwardingL
You will be asked username, hostname, port:host:hostport and passwd.
If everything works fine, you will get the shell prompt.
Try the port on localhost.
- StreamForwarding.java
This program will demonstrate the stream forwarding. The given Java
I/O streams will be forwared to the given remote host and port on
the remote side. It is simmilar to the -L option of ssh command,
but you don't have to assign and open a local tcp port.
$ CLASSPATH=.:../build javac StreamForwarding.java
$ CLASSPATH=.:../build java StreamForwarding
You will be asked username, hostname, host:hostport and passwd.
If everything works fine, System.in and System.out streams will be
forwared to remote port and you can send messages from command line.
- UserAuthPubKey.java
This program will demonstrate the user authentification by public key.
$ CLASSPATH=.:../build javac UserAuthPubKey.java
$ CLASSPATH=.:../build java UserAuthPubKey
You will be asked username, hostname, privatekey(id_dsa) and passphrase.
If everything works fine, you will get the shell prompt
- Compression.java
This program will demonstrate the packet compression.
$ CLASSPATH=.:../build javac Compression.java
$ CLASSPATH=.:../build java Compression
You will be asked username, hostname and passwd.
If everything works fine, you will get the shell prompt.
In this program, all data from sshd server to jsch will be
compressed.
- ScpTo.java
This program will demonstrate the file transfer from local to remote.
$ CLASSPATH=.:../build javac ScpTo.java
$ CLASSPATH=.:../build java ScpTo file1 user@remotehost:file2
You will be asked passwd.
If everything works fine, a local file 'file1' will copied to
'file2' on 'remotehost'.
- ScpFrom.java
This program will demonstrate the file transfer from remote to local
$ CLASSPATH=.:../build javac ScpFrom.java
$ CLASSPATH=.:../build java ScpFrom user@remotehost:file1 file2
You will be asked passwd.
If everything works fine, a file 'file1' on 'remotehost' will copied to
local 'file1'.
- Sftp.java
This program will demonstrate the sftp protocol support.
$ CLASSPATH=.:../build javac Sftp.java
$ CLASSPATH=.:../build java Sftp
You will be asked username, host and passwd.
If everything works fine, you will get a prompt 'sftp>'.
'help' command will show available command.
In current implementation, the destination path for 'get' and 'put'
commands must be a file, not a directory.
- KnownHosts.java
This program will demonstrate the 'known_hosts' file handling.
$ CLASSPATH=.:../build javac KnownHosts.java
$ CLASSPATH=.:../build java KnownHosts
You will be asked username, hostname, a path for 'known_hosts' and passwd.
If everything works fine, you will get the shell prompt.
In current implementation, jsch only reads 'known_hosts' for checking
and does not modify it.
- UserAuthKI.java
This program will demonstrate the keyboard-interactive authentication.
$ CLASSPATH=.:../build javac UserAuthKI.java
$ CLASSPATH=.:../build java UserAuthKI
If the remote sshd supports keyboard-interactive authentication,
you will be prompted.
- KeyGen.java
This progam will demonstrate the DSA keypair generation.
$ CLASSPATH=.:../build javac KeyGen.java
$ CLASSPATH=.:../build java KeyGen rsa output_keyfile comment
or
$ CLASSPATH=.:../build java KeyGen dsa output_keyfile comment
You will be asked a passphrase for output_keyfile.
If everything works fine, you will get the DSA or RSA keypair,
output_keyfile and output_keyfile+".pub".
The private key and public key are in the OpenSSH format.
- ChangePassphrase.java
This program will demonstrate to change the passphrase for a
private key file instead of creating a new private key.
$ CLASSPATH=.:../build javac ChangePassphrase.java
$ CLASSPATH=.:../build java ChangePassphrase private-key
A passphrase will be prompted if the given private-key has been
encrypted. After successfully loading the content of the
private-key, the new passphrase will be prompted and the given
private-key will be re-encrypted with that new passphrase.
- AES.java
This program will demonstrate how to use "aes128-cbc".
- Daemon.java
This program will demonstrate how to provide a network service like
inetd by using remote port-forwarding functionality.
- Logger.java
This program will demonstrate how to enable logging mechanism and
get logging messages.
- Subsystem.java
This program will demonstrate how to use the Subsystem channel.
- Sudo.java
This program will demonstrate how to exec 'sudo' on the remote.
- ScpToNoneCipher.java
This program will demonstrate how to enable none cipher.
- JumpHosts.java
This program will demonstrate SSH through jump hosts.
- OpenSSHConfig.java
This program will demonstrate how OpenSSH's config is supported.
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/**
* This program will demonstrate how to use "aes128-cbc".
*
*/
import com.jcraft.jsch.*;
import java.awt.*;
import javax.swing.*;
public class AES{
public static void main(String[] arg){
try{
JSch jsch = new JSch();
//jsch.setKnownHosts("/home/foo/.ssh/known_hosts");
String host=null;
if(arg.length>0){
host=arg[0];
}
else{
host=JOptionPane.showInputDialog("Enter username@hostname",
System.getProperty("user.name")+
"@localhost");
}
String user=host.substring(0, host.indexOf('@'));
host=host.substring(host.indexOf('@')+1);
Session session=jsch.getSession(user, host, 22);
//session.setPassword("your password");
// username and password will be given via UserInfo interface.
UserInfo ui=new MyUserInfo();
session.setUserInfo(ui);
session.setConfig("cipher.s2c", "aes128-cbc,3des-cbc,blowfish-cbc");
session.setConfig("cipher.c2s", "aes128-cbc,3des-cbc,blowfish-cbc");
session.setConfig("CheckCiphers", "aes128-cbc");
session.connect();
Channel channel=session.openChannel("shell");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect();
}
catch(Exception e){
System.out.println(e);
}
}
public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{
public String getPassword(){ return passwd; }
public boolean promptYesNo(String str){
Object[] options={ "yes", "no" };
int foo=JOptionPane.showOptionDialog(null,
str,
"Warning",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE,
null, options, options[0]);
return foo==0;
}
String passwd;
JTextField passwordField=(JTextField)new JPasswordField(20);
public String getPassphrase(){ return null; }
public boolean promptPassphrase(String message){ return true; }
public boolean promptPassword(String message){
Object[] ob={passwordField};
int result=
JOptionPane.showConfirmDialog(null, ob, message,
JOptionPane.OK_CANCEL_OPTION);
if(result==JOptionPane.OK_OPTION){
passwd=passwordField.getText();
return true;
}
else{
return false;
}
}
public void showMessage(String message){
JOptionPane.showMessageDialog(null, message);
}
final GridBagConstraints gbc =
new GridBagConstraints(0,0,1,1,1,1,
GridBagConstraints.NORTHWEST,
GridBagConstraints.NONE,
new Insets(0,0,0,0),0,0);
private Container panel;
public String[] promptKeyboardInteractive(String destination,
String name,
String instruction,
String[] prompt,
boolean[] echo){
panel = new JPanel();
panel.setLayout(new GridBagLayout());
gbc.weightx = 1.0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.gridx = 0;
panel.add(new JLabel(instruction), gbc);
gbc.gridy++;
gbc.gridwidth = GridBagConstraints.RELATIVE;
JTextField[] texts=new JTextField[prompt.length];
for(int i=0; i<prompt.length; i++){
gbc.fill = GridBagConstraints.NONE;
gbc.gridx = 0;
gbc.weightx = 1;
panel.add(new JLabel(prompt[i]),gbc);
gbc.gridx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weighty = 1;
if(echo[i]){
texts[i]=new JTextField(20);
}
else{
texts[i]=new JPasswordField(20);
}
panel.add(texts[i], gbc);
gbc.gridy++;
}
if(JOptionPane.showConfirmDialog(null, panel,
destination+": "+name,
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE)
==JOptionPane.OK_OPTION){
String[] response=new String[prompt.length];
for(int i=0; i<prompt.length; i++){
response[i]=texts[i].getText();
}
return response;
}
else{
return null; // cancel
}
}
}
}
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/**
* This program will demonstrate to change the passphrase for a
* private key file instead of creating a new private key.
* $ CLASSPATH=.:../build javac ChangePassphrase.java
* $ CLASSPATH=.:../build java ChangePassphrase private-key
* A passphrase will be prompted if the given private-key has been
* encrypted. After successfully loading the content of the
* private-key, the new passphrase will be prompted and the given
* private-key will be re-encrypted with that new passphrase.
*
*/
import com.jcraft.jsch.*;
import javax.swing.*;
class ChangePassphrase{
public static void main(String[] arg){
if(arg.length!=1){
System.err.println("usage: java ChangePassphrase private_key");
System.exit(-1);
}
JSch jsch=new JSch();
String pkey=arg[0];
try{
KeyPair kpair=KeyPair.load(jsch, pkey);
System.out.println(pkey+" has "+(kpair.isEncrypted()?"been ":"not been ")+"encrypted");
String passphrase="";
while(kpair.isEncrypted()){
JTextField passphraseField=(JTextField)new JPasswordField(20);
Object[] ob={passphraseField};
int result=JOptionPane.showConfirmDialog(null, ob,
"Enter passphrase for "+pkey,
JOptionPane.OK_CANCEL_OPTION);
if(result!=JOptionPane.OK_OPTION){
System.exit(-1);
}
passphrase=passphraseField.getText();
if(!kpair.decrypt(passphrase)){
System.out.println("failed to decrypt "+pkey);
}
else{
System.out.println(pkey+" is decrypted.");
}
}
passphrase="";
JTextField passphraseField=(JTextField)new JPasswordField(20);
Object[] ob={passphraseField};
int result=JOptionPane.showConfirmDialog(null, ob,
"Enter new passphrase for "+pkey+
" (empty for no passphrase)",
JOptionPane.OK_CANCEL_OPTION);
if(result!=JOptionPane.OK_OPTION){
System.exit(-1);
}
passphrase=passphraseField.getText();
kpair.setPassphrase(passphrase);
kpair.writePrivateKey(pkey);
kpair.dispose();
}
catch(Exception e){
System.out.println(e);
}
System.exit(0);
}
}
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/**
* This program will demonstrate the packet compression.
* $ CLASSPATH=.:../build javac Compression.java
* $ CLASSPATH=.:../build java Compression
* You will be asked username, hostname and passwd.
* If everything works fine, you will get the shell prompt.
* In this program, all data from sshd server to jsch will be compressed.
*
*/
import com.jcraft.jsch.*;
import java.awt.*;
import javax.swing.*;
public class Compression{
public static void main(String[] arg){
try{
JSch jsch=new JSch();
String host=null;
if(arg.length>0){
host=arg[0];
}
else{
host=JOptionPane.showInputDialog("Enter username@hostname",
System.getProperty("user.name")+
"@localhost");
}
String user=host.substring(0, host.indexOf('@'));
host=host.substring(host.indexOf('@')+1);
Session session=jsch.getSession(user, host, 22);
// username and password will be given via UserInfo interface.
UserInfo ui=new MyUserInfo();
session.setUserInfo(ui);
session.setConfig("compression.s2c", "zlib@openssh.com,zlib,none");
session.setConfig("compression.c2s", "zlib@openssh.com,zlib,none");
session.setConfig("compression_level", "9");
session.connect();
Channel channel=session.openChannel("shell");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect();
}
catch(Exception e){
System.out.println(e);
}
}
public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{
public String getPassword(){ return passwd; }
public boolean promptYesNo(String str){
Object[] options={ "yes", "no" };
int foo=JOptionPane.showOptionDialog(null,
str,
"Warning",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE,
null, options, options[0]);
return foo==0;
}
String passwd;
JTextField passwordField=(JTextField)new JPasswordField(20);
public String getPassphrase(){ return null; }
public boolean promptPassphrase(String message){ return true; }
public boolean promptPassword(String message){
Object[] ob={passwordField};
int result=
JOptionPane.showConfirmDialog(null, ob, message,
JOptionPane.OK_CANCEL_OPTION);
if(result==JOptionPane.OK_OPTION){
passwd=passwordField.getText();
return true;
}
else{ return false; }
}
public void showMessage(String message){
JOptionPane.showMessageDialog(null, message);
}
final GridBagConstraints gbc =
new GridBagConstraints(0,0,1,1,1,1,
GridBagConstraints.NORTHWEST,
GridBagConstraints.NONE,
new Insets(0,0,0,0),0,0);
private Container panel;
public String[] promptKeyboardInteractive(String destination,
String name,
String instruction,
String[] prompt,
boolean[] echo){
panel = new JPanel();
panel.setLayout(new GridBagLayout());
gbc.weightx = 1.0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.gridx = 0;
panel.add(new JLabel(instruction), gbc);
gbc.gridy++;
gbc.gridwidth = GridBagConstraints.RELATIVE;
JTextField[] texts=new JTextField[prompt.length];
for(int i=0; i<prompt.length; i++){
gbc.fill = GridBagConstraints.NONE;
gbc.gridx = 0;
gbc.weightx = 1;
panel.add(new JLabel(prompt[i]),gbc);
gbc.gridx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weighty = 1;
if(echo[i]){
texts[i]=new JTextField(20);
}
else{
texts[i]=new JPasswordField(20);
}
panel.add(texts[i], gbc);
gbc.gridy++;
}
if(JOptionPane.showConfirmDialog(null, panel,
destination+": "+name,
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE)
==JOptionPane.OK_OPTION){
String[] response=new String[prompt.length];
for(int i=0; i<prompt.length; i++){
response[i]=texts[i].getText();
}
return response;
}
else{
return null; // cancel
}
}
}
}
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/**
* This program will demonstrate how to provide a network service like
* inetd by using remote port-forwarding functionality.
*
*/
import com.jcraft.jsch.*;
import java.io.*;
import java.awt.*;
import javax.swing.*;
public class Daemon{
public static void main(String[] arg){
int rport;
try{
JSch jsch=new JSch();
String host=null;
if(arg.length>0){
host=arg[0];
}
else{
host=JOptionPane.showInputDialog("Enter username@hostname",
System.getProperty("user.name")+
"@localhost");
}
String user=host.substring(0, host.indexOf('@'));
host=host.substring(host.indexOf('@')+1);
Session session=jsch.getSession(user, host, 22);
String foo=JOptionPane.showInputDialog("Enter remote port number",
"8888");
rport=Integer.parseInt(foo);
// username and password will be given via UserInfo interface.
UserInfo ui=new MyUserInfo();
session.setUserInfo(ui);
session.connect();
//session.setPortForwardingR(rport, Parrot.class.getName());
session.setPortForwardingR(rport, "Daemon$Parrot");
System.out.println(host+":"+rport+" <--> "+"Parrot");
}
catch(Exception e){
System.out.println(e);
}
}
public static class Parrot implements ForwardedTCPIPDaemon{
ChannelForwardedTCPIP channel;
Object[] arg;
InputStream in;
OutputStream out;
public void setChannel(ChannelForwardedTCPIP c, InputStream in, OutputStream out){
this.channel=c;
this.in=in;
this.out=out;
}
public void setArg(Object[] arg){this.arg=arg;}
public void run(){
try{
byte[] buf=new byte[1024];
System.out.println("remote port: "+channel.getRemotePort());
System.out.println("remote host: "+channel.getSession().getHost());
while(true){
int i=in.read(buf, 0, buf.length);
if(i<=0)break;
out.write(buf, 0, i);
out.flush();
if(buf[0]=='.')break;
}
}
catch(JSchException e){
System.out.println("session is down.");
}
catch(IOException e){
}
}
}
public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{
public String getPassword(){ return passwd; }
public boolean promptYesNo(String str){
Object[] options={ "yes", "no" };
int foo=JOptionPane.showOptionDialog(null,
str,
"Warning",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE,
null, options, options[0]);
return foo==0;
}
String passwd;
JTextField passwordField=(JTextField)new JPasswordField(20);
public String getPassphrase(){ return null; }
public boolean promptPassphrase(String message){ return true; }
public boolean promptPassword(String message){
Object[] ob={passwordField};
int result=JOptionPane.showConfirmDialog(null, ob, message,
JOptionPane.OK_CANCEL_OPTION);
if(result==JOptionPane.OK_OPTION){
passwd=passwordField.getText();
return true;
}
else{ return false; }
}
public void showMessage(String message){
JOptionPane.showMessageDialog(null, message);
}
final GridBagConstraints gbc =
new GridBagConstraints(0,0,1,1,1,1,
GridBagConstraints.NORTHWEST,
GridBagConstraints.NONE,
new Insets(0,0,0,0),0,0);
private Container panel;
public String[] promptKeyboardInteractive(String destination,
String name,
String instruction,
String[] prompt,
boolean[] echo){
panel = new JPanel();
panel.setLayout(new GridBagLayout());
gbc.weightx = 1.0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.gridx = 0;
panel.add(new JLabel(instruction), gbc);
gbc.gridy++;
gbc.gridwidth = GridBagConstraints.RELATIVE;
JTextField[] texts=new JTextField[prompt.length];
for(int i=0; i<prompt.length; i++){
gbc.fill = GridBagConstraints.NONE;
gbc.gridx = 0;
gbc.weightx = 1;
panel.add(new JLabel(prompt[i]),gbc);
gbc.gridx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weighty = 1;
if(echo[i]){
texts[i]=new JTextField(20);
}
else{
texts[i]=new JPasswordField(20);
}
panel.add(texts[i], gbc);
gbc.gridy++;
}
if(JOptionPane.showConfirmDialog(null, panel,
destination+": "+name,
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE)
==JOptionPane.OK_OPTION){
String[] response=new String[prompt.length];
for(int i=0; i<prompt.length; i++){
response[i]=texts[i].getText();
}
return response;
}
else{
return null; // cancel
}
}
}
}
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/**
* This program will demonstrate remote exec.
* $ CLASSPATH=.:../build javac Exec.java
* $ CLASSPATH=.:../build java Exec
* You will be asked username, hostname, displayname, passwd and command.
* If everything works fine, given command will be invoked
* on the remote side and outputs will be printed out.
*
*/
import com.jcraft.jsch.*;
import java.awt.*;
import javax.swing.*;
import java.io.*;
public class Exec{
public static void main(String[] arg){
try{
JSch jsch=new JSch();
String host=null;
if(arg.length>0){
host=arg[0];
}
else{
host=JOptionPane.showInputDialog("Enter username@hostname",
System.getProperty("user.name")+
"@localhost");
}
String user=host.substring(0, host.indexOf('@'));
host=host.substring(host.indexOf('@')+1);
Session session=jsch.getSession(user, host, 22);
/*
String xhost="127.0.0.1";
int xport=0;
String display=JOptionPane.showInputDialog("Enter display name",
xhost+":"+xport);
xhost=display.substring(0, display.indexOf(':'));
xport=Integer.parseInt(display.substring(display.indexOf(':')+1));
session.setX11Host(xhost);
session.setX11Port(xport+6000);
*/
// username and password will be given via UserInfo interface.
UserInfo ui=new MyUserInfo();
session.setUserInfo(ui);
session.connect();
String command=JOptionPane.showInputDialog("Enter command",
"set|grep SSH");
Channel channel=session.openChannel("exec");
((ChannelExec)channel).setCommand(command);
// X Forwarding
// channel.setXForwarding(true);
//channel.setInputStream(System.in);
channel.setInputStream(null);
//channel.setOutputStream(System.out);
//FileOutputStream fos=new FileOutputStream("/tmp/stderr");
//((ChannelExec)channel).setErrStream(fos);
((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(Exception e){
System.out.println(e);
}
}
public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{
public String getPassword(){ return passwd; }
public boolean promptYesNo(String str){
Object[] options={ "yes", "no" };
int foo=JOptionPane.showOptionDialog(null,
str,
"Warning",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE,
null, options, options[0]);
return foo==0;
}
String passwd;
JTextField passwordField=(JTextField)new JPasswordField(20);
public String getPassphrase(){ return null; }
public boolean promptPassphrase(String message){ return true; }
public boolean promptPassword(String message){
Object[] ob={passwordField};
int result=
JOptionPane.showConfirmDialog(null, ob, message,
JOptionPane.OK_CANCEL_OPTION);
if(result==JOptionPane.OK_OPTION){
passwd=passwordField.getText();
return true;
}
else{
return false;
}
}
public void showMessage(String message){
JOptionPane.showMessageDialog(null, message);
}
final GridBagConstraints gbc =
new GridBagConstraints(0,0,1,1,1,1,
GridBagConstraints.NORTHWEST,
GridBagConstraints.NONE,
new Insets(0,0,0,0),0,0);
private Container panel;
public String[] promptKeyboardInteractive(String destination,
String name,
String instruction,
String[] prompt,
boolean[] echo){
panel = new JPanel();
panel.setLayout(new GridBagLayout());
gbc.weightx = 1.0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.gridx = 0;
panel.add(new JLabel(instruction), gbc);
gbc.gridy++;
gbc.gridwidth = GridBagConstraints.RELATIVE;
JTextField[] texts=new JTextField[prompt.length];
for(int i=0; i<prompt.length; i++){
gbc.fill = GridBagConstraints.NONE;
gbc.gridx = 0;
gbc.weightx = 1;
panel.add(new JLabel(prompt[i]),gbc);
gbc.gridx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weighty = 1;
if(echo[i]){
texts[i]=new JTextField(20);
}
else{
texts[i]=new JPasswordField(20);
}
panel.add(texts[i], gbc);
gbc.gridy++;
}
if(JOptionPane.showConfirmDialog(null, panel,
destination+": "+name,
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE)
==JOptionPane.OK_OPTION){
String[] response=new String[prompt.length];
for(int i=0; i<prompt.length; i++){
response[i]=texts[i].getText();
}
return response;
}
else{
return null; // cancel
}
}
}
}
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/**
* This program will demonstrate SSH through jump hosts.
* Suppose that you don't have direct accesses to host2 and host3.
* $ CLASSPATH=.:../build javac JumpHosts.java
* $ CLASSPATH=.:../build java JumpHosts usr1@host1 usr2@host2 usr3@host3
* You will be asked passwords for those destinations,
* and if everything works fine, you will get file lists of your home-directory
* at host3.
*
*/
import com.jcraft.jsch.*;
import java.awt.*;
import javax.swing.*;
public class JumpHosts {
public static void main(String[] arg){
try{
JSch jsch = new JSch();
if(arg.length <= 1){
System.out.println("This program expects more arguments.");
System.exit(-1);
}
Session session = null;
Session[] sessions = new Session[arg.length];
String host = arg[0];
String user = host.substring(0, host.indexOf('@'));
host = host.substring(host.indexOf('@')+1);
sessions[0] = session = jsch.getSession(user, host, 22);
session.setUserInfo(new MyUserInfo());
session.connect();
System.out.println("The session has been established to "+user+"@"+host);
for(int i = 1; i < arg.length; i++){
host = arg[i];
user = host.substring(0, host.indexOf('@'));
host = host.substring(host.indexOf('@')+1);
int assinged_port = session.setPortForwardingL(0, host, 22);
System.out.println("portforwarding: "+
"localhost:"+assinged_port+" -> "+host+":"+22);
sessions[i] = session =
jsch.getSession(user, "127.0.0.1", assinged_port);
session.setUserInfo(new MyUserInfo());
session.setHostKeyAlias(host);
session.connect();
System.out.println("The session has been established to "+
user+"@"+host);
}
ChannelSftp sftp = (ChannelSftp)session.openChannel("sftp");
sftp.connect();
sftp.ls(".",
new ChannelSftp.LsEntrySelector() {
public int select(ChannelSftp.LsEntry le) {
System.out.println(le);
return ChannelSftp.LsEntrySelector.CONTINUE;
}
});
sftp.disconnect();
for(int i = sessions.length-1; i >= 0; i--){
sessions[i].disconnect();
}
}
catch(Exception e){
System.out.println(e);
}
}
public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{
public String getPassword(){ return passwd; }
public boolean promptYesNo(String str){
Object[] options={ "yes", "no" };
int foo=JOptionPane.showOptionDialog(null,
str,
"Warning",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE,
null, options, options[0]);
return foo==0;
}
String passwd;
JTextField passwordField=(JTextField)new JPasswordField(20);
public String getPassphrase(){ return null; }
public boolean promptPassphrase(String message){ return true; }
public boolean promptPassword(String message){
Object[] ob={passwordField};
int result=
JOptionPane.showConfirmDialog(null, ob, message,
JOptionPane.OK_CANCEL_OPTION);
if(result==JOptionPane.OK_OPTION){
passwd=passwordField.getText();
return true;
}
else{ return false; }
}
public void showMessage(String message){
JOptionPane.showMessageDialog(null, message);
}
final GridBagConstraints gbc =
new GridBagConstraints(0,0,1,1,1,1,
GridBagConstraints.NORTHWEST,
GridBagConstraints.NONE,
new Insets(0,0,0,0),0,0);
private Container panel;
public String[] promptKeyboardInteractive(String destination,
String name,
String instruction,
String[] prompt,
boolean[] echo){
panel = new JPanel();
panel.setLayout(new GridBagLayout());
gbc.weightx = 1.0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.gridx = 0;
panel.add(new JLabel(instruction), gbc);
gbc.gridy++;
gbc.gridwidth = GridBagConstraints.RELATIVE;
JTextField[] texts=new JTextField[prompt.length];
for(int i=0; i<prompt.length; i++){
gbc.fill = GridBagConstraints.NONE;
gbc.gridx = 0;
gbc.weightx = 1;
panel.add(new JLabel(prompt[i]),gbc);
gbc.gridx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weighty = 1;
if(echo[i]){
texts[i]=new JTextField(20);
}
else{
texts[i]=new JPasswordField(20);
}
panel.add(texts[i], gbc);
gbc.gridy++;
}
if(JOptionPane.showConfirmDialog(null, panel,
destination+": "+name,
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE)
==JOptionPane.OK_OPTION){
String[] response=new String[prompt.length];
for(int i=0; i<prompt.length; i++){
response[i]=texts[i].getText();
}
return response;
}
else{
return null; // cancel
}
}
}
}
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/**
* This progam will demonstrate the DSA keypair generation.
* $ CLASSPATH=.:../build javac KeyGen.java
* $ CLASSPATH=.:../build java KeyGen rsa output_keyfile comment
* or
* $ CLASSPATH=.:../build java KeyGen dsa output_keyfile comment
* You will be asked a passphrase for output_keyfile.
* If everything works fine, you will get the DSA or RSA keypair,
* output_keyfile and output_keyfile+".pub".
* The private key and public key are in the OpenSSH format.
*
*/
import com.jcraft.jsch.*;
import javax.swing.*;
class KeyGen{
public static void main(String[] arg){
if(arg.length<3){
System.err.println(
"usage: java KeyGen rsa output_keyfile comment\n"+
" java KeyGen dsa output_keyfile comment");
System.exit(-1);
}
String _type=arg[0];
int type=0;
if(_type.equals("rsa")){type=KeyPair.RSA;}
else if(_type.equals("dsa")){type=KeyPair.DSA;}
else {
System.err.println(
"usage: java KeyGen rsa output_keyfile comment\n"+
" java KeyGen dsa output_keyfile comment");
System.exit(-1);
}
String filename=arg[1];
String comment=arg[2];
JSch jsch=new JSch();
String passphrase="";
JTextField passphraseField=(JTextField)new JPasswordField(20);
Object[] ob={passphraseField};
int result=
JOptionPane.showConfirmDialog(null, ob, "Enter passphrase (empty for no passphrase)",
JOptionPane.OK_CANCEL_OPTION);
if(result==JOptionPane.OK_OPTION){
passphrase=passphraseField.getText();
}
try{
KeyPair kpair=KeyPair.genKeyPair(jsch, type);
kpair.setPassphrase(passphrase);
kpair.writePrivateKey(filename);
kpair.writePublicKey(filename+".pub", comment);
System.out.println("Finger print: "+kpair.getFingerPrint());
kpair.dispose();
}
catch(Exception e){
System.out.println(e);
}
System.exit(0);
}
}
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/**
* This program will demonstrate the 'known_hosts' file handling.
* $ CLASSPATH=.:../build javac KnownHosts.java
* $ CLASSPATH=.:../build java KnownHosts
* You will be asked username, hostname, a path for 'known_hosts' and passwd.
* If everything works fine, you will get the shell prompt.
* In current implementation, jsch only reads 'known_hosts' for checking
* and does not modify it.
*
*/
import com.jcraft.jsch.*;
import java.awt.*;
import javax.swing.*;
public class KnownHosts{
public static void main(String[] arg){
try{
JSch jsch=new JSch();
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Choose your known_hosts(ex. ~/.ssh/known_hosts)");
chooser.setFileHidingEnabled(false);
int returnVal=chooser.showOpenDialog(null);
if(returnVal==JFileChooser.APPROVE_OPTION) {
System.out.println("You chose "+
chooser.getSelectedFile().getAbsolutePath()+".");
jsch.setKnownHosts(chooser.getSelectedFile().getAbsolutePath());
}
HostKeyRepository hkr=jsch.getHostKeyRepository();
HostKey[] hks=hkr.getHostKey();
if(hks!=null){
System.out.println("Host keys in "+hkr.getKnownHostsRepositoryID());
for(int i=0; i<hks.length; i++){
HostKey hk=hks[i];
System.out.println(hk.getHost()+" "+
hk.getType()+" "+
hk.getFingerPrint(jsch));
}
System.out.println("");
}
String host=null;
if(arg.length>0){
host=arg[0];
}
else{
host=JOptionPane.showInputDialog("Enter username@hostname",
System.getProperty("user.name")+
"@localhost");
}
String user=host.substring(0, host.indexOf('@'));
host=host.substring(host.indexOf('@')+1);
Session session=jsch.getSession(user, host, 22);
// username and password will be given via UserInfo interface.
UserInfo ui=new MyUserInfo();
session.setUserInfo(ui);
/*
// In adding to known_hosts file, host names will be hashed.
session.setConfig("HashKnownHosts", "yes");
*/
session.connect();
{
HostKey hk=session.getHostKey();
System.out.println("HostKey: "+
hk.getHost()+" "+
hk.getType()+" "+
hk.getFingerPrint(jsch));
}
Channel channel=session.openChannel("shell");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect();
}
catch(Exception e){
System.out.println(e);
}
}
public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{
public String getPassword(){ return passwd; }
public boolean promptYesNo(String str){
Object[] options={ "yes", "no" };
int foo=JOptionPane.showOptionDialog(null,
str,
"Warning",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE,
null, options, options[0]);
return foo==0;
}
String passwd;
JTextField passwordField=(JTextField)new JPasswordField(20);
public String getPassphrase(){ return null; }
public boolean promptPassphrase(String message){ return true; }
public boolean promptPassword(String message){
Object[] ob={passwordField};
int result=
JOptionPane.showConfirmDialog(null, ob, message,
JOptionPane.OK_CANCEL_OPTION);
if(result==JOptionPane.OK_OPTION){
passwd=passwordField.getText();
return true;
}
else{ return false; }
}
public void showMessage(String message){
JOptionPane.showMessageDialog(null, message);
}
final GridBagConstraints gbc =
new GridBagConstraints(0,0,1,1,1,1,
GridBagConstraints.NORTHWEST,
GridBagConstraints.NONE,
new Insets(0,0,0,0),0,0);
private Container panel;
public String[] promptKeyboardInteractive(String destination,
String name,
String instruction,
String[] prompt,
boolean[] echo){
panel = new JPanel();
panel.setLayout(new GridBagLayout());
gbc.weightx = 1.0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.gridx = 0;
panel.add(new JLabel(instruction), gbc);
gbc.gridy++;
gbc.gridwidth = GridBagConstraints.RELATIVE;
JTextField[] texts=new JTextField[prompt.length];
for(int i=0; i<prompt.length; i++){
gbc.fill = GridBagConstraints.NONE;
gbc.gridx = 0;
gbc.weightx = 1;
panel.add(new JLabel(prompt[i]),gbc);
gbc.gridx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weighty = 1;
if(echo[i]){
texts[i]=new JTextField(20);
}
else{
texts[i]=new JPasswordField(20);
}
panel.add(texts[i], gbc);
gbc.gridy++;
}
if(JOptionPane.showConfirmDialog(null, panel,
destination+": "+name,
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE)
==JOptionPane.OK_OPTION){
String[] response=new String[prompt.length];
for(int i=0; i<prompt.length; i++){
response[i]=texts[i].getText();
}
return response;
}
else{
return null; // cancel
}
}
}
}
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/**
* This program will demonstrate how to enable logging mechanism and
* get logging messages.
*/
import com.jcraft.jsch.*;
import java.awt.*;
import javax.swing.*;
public class Logger{
public static void main(String[] arg){
try{
JSch.setLogger(new MyLogger());
JSch jsch=new JSch();
String host=null;
if(arg.length>0){
host=arg[0];
}
else{
host=JOptionPane.showInputDialog("Enter username@hostname",
System.getProperty("user.name")+
"@localhost");
}
String user=host.substring(0, host.indexOf('@'));
host=host.substring(host.indexOf('@')+1);
Session session=jsch.getSession(user, host, 22);
// username and password will be given via UserInfo interface.
UserInfo ui=new MyUserInfo();
session.setUserInfo(ui);
session.connect();
Channel channel=session.openChannel("shell");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect();
}
catch(Exception e){
System.out.println(e);
}
}
public static class MyLogger implements com.jcraft.jsch.Logger {
static java.util.Hashtable name=new java.util.Hashtable();
static{
name.put(new Integer(DEBUG), "DEBUG: ");
name.put(new Integer(INFO), "INFO: ");
name.put(new Integer(WARN), "WARN: ");
name.put(new Integer(ERROR), "ERROR: ");
name.put(new Integer(FATAL), "FATAL: ");
}
public boolean isEnabled(int level){
return true;
}
public void log(int level, String message){
System.err.print(name.get(new Integer(level)));
System.err.println(message);
}
}
public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{
public String getPassword(){ return passwd; }
public boolean promptYesNo(String str){
Object[] options={ "yes", "no" };
int foo=JOptionPane.showOptionDialog(null,
str,
"Warning",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE,
null, options, options[0]);
return foo==0;
}
String passwd;
JTextField passwordField=(JTextField)new JPasswordField(20);
public String getPassphrase(){ return null; }
public boolean promptPassphrase(String message){ return true; }
public boolean promptPassword(String message){
Object[] ob={passwordField};
int result=JOptionPane.showConfirmDialog(null, ob, message,
JOptionPane.OK_CANCEL_OPTION);
if(result==JOptionPane.OK_OPTION){
passwd=passwordField.getText();
return true;
}
else{
return false;
}
}
public void showMessage(String message){
JOptionPane.showMessageDialog(null, message);
}
final GridBagConstraints gbc =
new GridBagConstraints(0,0,1,1,1,1,
GridBagConstraints.NORTHWEST,
GridBagConstraints.NONE,
new Insets(0,0,0,0),0,0);
private Container panel;
public String[] promptKeyboardInteractive(String destination,
String name,
String instruction,
String[] prompt,
boolean[] echo){
panel = new JPanel();
panel.setLayout(new GridBagLayout());
gbc.weightx = 1.0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.gridx = 0;
panel.add(new JLabel(instruction), gbc);
gbc.gridy++;
gbc.gridwidth = GridBagConstraints.RELATIVE;
JTextField[] texts=new JTextField[prompt.length];
for(int i=0; i<prompt.length; i++){
gbc.fill = GridBagConstraints.NONE;
gbc.gridx = 0;
gbc.weightx = 1;
panel.add(new JLabel(prompt[i]),gbc);
gbc.gridx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weighty = 1;
if(echo[i]){
texts[i]=new JTextField(20);
}
else{
texts[i]=new JPasswordField(20);
}
panel.add(texts[i], gbc);
gbc.gridy++;
}
if(JOptionPane.showConfirmDialog(null, panel,
destination+": "+name,
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE)
==JOptionPane.OK_OPTION){
String[] response=new String[prompt.length];
for(int i=0; i<prompt.length; i++){
response[i]=texts[i].getText();
}
return response;
}
else{
return null; // cancel
}
}
}
}
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/**
* This program demonsrates how to use OpenSSHConfig class.
* $ CLASSPATH=.:../build javac OpenSSHConfig.java
* $ CLASSPATH=.:../build java OpenSSHConfig
* You will be asked username, hostname and passwd.
* If everything works fine, you will get the shell prompt. Output may
* be ugly because of lacks of terminal-emulation, but you can issue commands.
*
*/
import com.jcraft.jsch.*;
import java.awt.*;
import javax.swing.*;
public class OpenSSHConfig {
public static void main(String[] arg){
try{
JSch jsch=new JSch();
String host=null;
if(arg.length>0){
host=arg[0];
}
else{
host=JOptionPane.showInputDialog("Enter username@hostname",
System.getProperty("user.name")+
"@localhost");
}
String user=host.substring(0, host.indexOf('@'));
host=host.substring(host.indexOf('@')+1);
String config =
"Port 22\n"+
"\n"+
"Host foo\n"+
" User "+user+"\n"+
" Hostname "+host+"\n"+
"Host *\n"+
" ConnectTime 30000\n"+
" PreferredAuthentications keyboard-interactive,password,publickey\n"+
" #ForwardAgent yes\n"+
" #StrictHostKeyChecking no\n"+
" #IdentityFile ~/.ssh/id_rsa\n"+
" #UserKnownHostsFile ~/.ssh/known_hosts";
System.out.println("Generated configurations:");
System.out.println(config);
ConfigRepository configRepository =
com.jcraft.jsch.OpenSSHConfig.parse(config);
//com.jcraft.jsch.OpenSSHConfig.parseFile("~/.ssh/config");
jsch.setConfigRepository(configRepository);
// "foo" is from "Host foo" in the above config.
Session session=jsch.getSession("foo");
String passwd = JOptionPane.showInputDialog("Enter password");
session.setPassword(passwd);
UserInfo ui = new MyUserInfo(){
public void showMessage(String message){
JOptionPane.showMessageDialog(null, message);
}
public boolean promptYesNo(String message){
Object[] options={ "yes", "no" };
int foo=JOptionPane.showOptionDialog(null,
message,
"Warning",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE,
null, options, options[0]);
return foo==0;
}
// If password is not given before the invocation of Session#connect(),
// implement also following methods,
// * UserInfo#getPassword(),
// * UserInfo#promptPassword(String message) and
// * UIKeyboardInteractive#promptKeyboardInteractive()
};
session.setUserInfo(ui);
session.connect(); // making a connection with timeout as defined above.
Channel channel=session.openChannel("shell");
channel.setInputStream(System.in);
/*
// a hack for MS-DOS prompt on Windows.
channel.setInputStream(new FilterInputStream(System.in){
public int read(byte[] b, int off, int len)throws IOException{
return in.read(b, off, (len>1024?1024:len));
}
});
*/
channel.setOutputStream(System.out);
/*
// Choose the pty-type "vt102".
((ChannelShell)channel).setPtyType("vt102");
*/
/*
// Set environment variable "LANG" as "ja_JP.eucJP".
((ChannelShell)channel).setEnv("LANG", "ja_JP.eucJP");
*/
//channel.connect();
channel.connect(3*1000);
}
catch(Exception e){
System.out.println(e);
}
}
public static abstract class MyUserInfo
implements UserInfo, UIKeyboardInteractive{
public String getPassword(){ return null; }
public boolean promptYesNo(String str){ return false; }
public String getPassphrase(){ return null; }
public boolean promptPassphrase(String message){ return false; }
public boolean promptPassword(String message){ return false; }
public void showMessage(String message){ }
public String[] promptKeyboardInteractive(String destination,
String name,
String instruction,
String[] prompt,
boolean[] echo){
return null;
}
}
}
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/**
* This program will demonstrate the port forwarding like option -L of
* ssh command; the given port on the local host will be forwarded to
* the given remote host and port on the remote side.
* $ CLASSPATH=.:../build javac PortForwardingL.java
* $ CLASSPATH=.:../build java PortForwardingL
* You will be asked username, hostname, port:host:hostport and passwd.
* If everything works fine, you will get the shell prompt.
* Try the port on localhost.
*
*/
import com.jcraft.jsch.*;
import java.awt.*;
import javax.swing.*;
public class PortForwardingL{
public static void main(String[] arg){
int lport;
String rhost;
int rport;
try{
JSch jsch=new JSch();
String host=null;
if(arg.length>0){
host=arg[0];
}
else{
host=JOptionPane.showInputDialog("Enter username@hostname",
System.getProperty("user.name")+
"@localhost");
}
String user=host.substring(0, host.indexOf('@'));
host=host.substring(host.indexOf('@')+1);
Session session=jsch.getSession(user, host, 22);
String foo=JOptionPane.showInputDialog("Enter -L port:host:hostport",
"port:host:hostport");
lport=Integer.parseInt(foo.substring(0, foo.indexOf(':')));
foo=foo.substring(foo.indexOf(':')+1);
rhost=foo.substring(0, foo.indexOf(':'));
rport=Integer.parseInt(foo.substring(foo.indexOf(':')+1));
// username and password will be given via UserInfo interface.
UserInfo ui=new MyUserInfo();
session.setUserInfo(ui);
session.connect();
//Channel channel=session.openChannel("shell");
//channel.connect();
int assinged_port=session.setPortForwardingL(lport, rhost, rport);
System.out.println("localhost:"+assinged_port+" -> "+rhost+":"+rport);
}
catch(Exception e){
System.out.println(e);
}
}
public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{
public String getPassword(){ return passwd; }
public boolean promptYesNo(String str){
Object[] options={ "yes", "no" };
int foo=JOptionPane.showOptionDialog(null,
str,
"Warning",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE,
null, options, options[0]);
return foo==0;
}
String passwd;
JTextField passwordField=(JTextField)new JPasswordField(20);
public String getPassphrase(){ return null; }
public boolean promptPassphrase(String message){ return true; }
public boolean promptPassword(String message){
Object[] ob={passwordField};
int result=
JOptionPane.showConfirmDialog(null, ob, message,
JOptionPane.OK_CANCEL_OPTION);
if(result==JOptionPane.OK_OPTION){
passwd=passwordField.getText();
return true;
}
else{ return false; }
}
public void showMessage(String message){
JOptionPane.showMessageDialog(null, message);
}
final GridBagConstraints gbc =
new GridBagConstraints(0,0,1,1,1,1,
GridBagConstraints.NORTHWEST,
GridBagConstraints.NONE,
new Insets(0,0,0,0),0,0);
private Container panel;
public String[] promptKeyboardInteractive(String destination,
String name,
String instruction,
String[] prompt,
boolean[] echo){
panel = new JPanel();
panel.setLayout(new GridBagLayout());
gbc.weightx = 1.0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.gridx = 0;
panel.add(new JLabel(instruction), gbc);
gbc.gridy++;
gbc.gridwidth = GridBagConstraints.RELATIVE;
JTextField[] texts=new JTextField[prompt.length];
for(int i=0; i<prompt.length; i++){
gbc.fill = GridBagConstraints.NONE;
gbc.gridx = 0;
gbc.weightx = 1;
panel.add(new JLabel(prompt[i]),gbc);
gbc.gridx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weighty = 1;
if(echo[i]){
texts[i]=new JTextField(20);
}
else{
texts[i]=new JPasswordField(20);
}
panel.add(texts[i], gbc);
gbc.gridy++;
}
if(JOptionPane.showConfirmDialog(null, panel,
destination+": "+name,
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE)
==JOptionPane.OK_OPTION){
String[] response=new String[prompt.length];
for(int i=0; i<prompt.length; i++){
response[i]=texts[i].getText();
}
return response;
}
else{
return null; // cancel
}
}
}
}
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/**
* This program will demonstrate the port forwarding like option -R of
* ssh command; the given port on the remote host will be forwarded to
* the given host and port on the local side.
* $ CLASSPATH=.:../build javac PortForwardingR.java
* $ CLASSPATH=.:../build java PortForwardingR
* You will be asked username, hostname, port:host:hostport and passwd.
* If everything works fine, you will get the shell prompt.
* Try the port on remote host.
*
*/
import com.jcraft.jsch.*;
import java.awt.*;
import javax.swing.*;
public class PortForwardingR{
public static void main(String[] arg){
int rport;
String lhost;
int lport;
try{
JSch jsch=new JSch();
String host=null;
if(arg.length>0){
host=arg[0];
}
else{
host=JOptionPane.showInputDialog("Enter username@hostname",
System.getProperty("user.name")+
"@localhost");
}
String user=host.substring(0, host.indexOf('@'));
host=host.substring(host.indexOf('@')+1);
Session session=jsch.getSession(user, host, 22);
String foo=JOptionPane.showInputDialog("Enter -R port:host:hostport",
"port:host:hostport");
rport=Integer.parseInt(foo.substring(0, foo.indexOf(':')));
foo=foo.substring(foo.indexOf(':')+1);
lhost=foo.substring(0, foo.indexOf(':'));
lport=Integer.parseInt(foo.substring(foo.indexOf(':')+1));
// username and password will be given via UserInfo interface.
UserInfo ui=new MyUserInfo();
session.setUserInfo(ui);
session.connect();
// Channel channel=session.openChannel("shell");
// channel.connect();
session.setPortForwardingR(rport, lhost, lport);
System.out.println(host+":"+rport+" -> "+lhost+":"+lport);
}
catch(Exception e){
System.out.println(e);
}
}
public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{
public String getPassword(){ return passwd; }
public boolean promptYesNo(String str){
Object[] options={ "yes", "no" };
int foo=JOptionPane.showOptionDialog(null,
str,
"Warning",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE,
null, options, options[0]);
return foo==0;
}
String passwd;
JTextField passwordField=(JTextField)new JPasswordField(20);
public String getPassphrase(){ return null; }
public boolean promptPassphrase(String message){ return true; }
public boolean promptPassword(String message){
Object[] ob={passwordField};
int result=
JOptionPane.showConfirmDialog(null, ob, message,
JOptionPane.OK_CANCEL_OPTION);
if(result==JOptionPane.OK_OPTION){
passwd=passwordField.getText();
return true;
}
else{ return false; }
}
public void showMessage(String message){
JOptionPane.showMessageDialog(null, message);
}
final GridBagConstraints gbc =
new GridBagConstraints(0,0,1,1,1,1,
GridBagConstraints.NORTHWEST,
GridBagConstraints.NONE,
new Insets(0,0,0,0),0,0);
private Container panel;
public String[] promptKeyboardInteractive(String destination,
String name,
String instruction,
String[] prompt,
boolean[] echo){
panel = new JPanel();
panel.setLayout(new GridBagLayout());
gbc.weightx = 1.0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.gridx = 0;
panel.add(new JLabel(instruction), gbc);
gbc.gridy++;
gbc.gridwidth = GridBagConstraints.RELATIVE;
JTextField[] texts=new JTextField[prompt.length];
for(int i=0; i<prompt.length; i++){
gbc.fill = GridBagConstraints.NONE;
gbc.gridx = 0;
gbc.weightx = 1;
panel.add(new JLabel(prompt[i]),gbc);
gbc.gridx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weighty = 1;
if(echo[i]){
texts[i]=new JTextField(20);
}
else{
texts[i]=new JPasswordField(20);
}
panel.add(texts[i], gbc);
gbc.gridy++;
}
if(JOptionPane.showConfirmDialog(null, panel,
destination+": "+name,
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE)
==JOptionPane.OK_OPTION){
String[] response=new String[prompt.length];
for(int i=0; i<prompt.length; i++){
response[i]=texts[i].getText();
}
return response;
}
else{
return null; // cancel
}
}
}
}
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/**
* This program will demonstrate the file transfer from remote to local
* $ CLASSPATH=.:../build javac ScpFrom.java
* $ CLASSPATH=.:../build java ScpFrom user@remotehost:file1 file2
* You will be asked passwd.
* If everything works fine, a file 'file1' on 'remotehost' will copied to
* local 'file1'.
*
*/
import com.jcraft.jsch.*;
import java.awt.*;
import javax.swing.*;
import java.io.*;
public class ScpFrom{
public static void main(String[] arg){
if(arg.length!=2){
System.err.println("usage: java ScpFrom user@remotehost:file1 file2");
System.exit(-1);
}
FileOutputStream fos=null;
try{
String user=arg[0].substring(0, arg[0].indexOf('@'));
arg[0]=arg[0].substring(arg[0].indexOf('@')+1);
String host=arg[0].substring(0, arg[0].indexOf(':'));
String rfile=arg[0].substring(arg[0].indexOf(':')+1);
String lfile=arg[1];
String prefix=null;
if(new File(lfile).isDirectory()){
prefix=lfile+File.separator;
}
JSch jsch=new JSch();
Session session=jsch.getSession(user, host, 22);
// username and password will be given via UserInfo interface.
UserInfo ui=new MyUserInfo();
session.setUserInfo(ui);
session.connect();
// exec 'scp -f rfile' remotely
String command="scp -f "+rfile;
Channel channel=session.openChannel("exec");
((ChannelExec)channel).setCommand(command);
// get I/O streams for remote scp
OutputStream out=channel.getOutputStream();
InputStream in=channel.getInputStream();
channel.connect();
byte[] buf=new byte[1024];
// send '\0'
buf[0]=0; out.write(buf, 0, 1); out.flush();
while(true){
int c=checkAck(in);
if(c!='C'){
break;
}
// read '0644 '
in.read(buf, 0, 5);
long filesize=0L;
while(true){
if(in.read(buf, 0, 1)<0){
// error
break;
}
if(buf[0]==' ')break;
filesize=filesize*10L+(long)(buf[0]-'0');
}
String file=null;
for(int i=0;;i++){
in.read(buf, i, 1);
if(buf[i]==(byte)0x0a){
file=new String(buf, 0, i);
break;
}
}
//System.out.println("filesize="+filesize+", file="+file);
// send '\0'
buf[0]=0; out.write(buf, 0, 1); out.flush();
// read a content of lfile
fos=new FileOutputStream(prefix==null ? lfile : prefix+file);
int foo;
while(true){
if(buf.length<filesize) foo=buf.length;
else foo=(int)filesize;
foo=in.read(buf, 0, foo);
if(foo<0){
// error
break;
}
fos.write(buf, 0, foo);
filesize-=foo;
if(filesize==0L) break;
}
fos.close();
fos=null;
if(checkAck(in)!=0){
System.exit(0);
}
// send '\0'
buf[0]=0; out.write(buf, 0, 1); out.flush();
}
session.disconnect();
System.exit(0);
}
catch(Exception e){
System.out.println(e);
try{if(fos!=null)fos.close();}catch(Exception ee){}
}
}
static int checkAck(InputStream in) throws IOException{
int b=in.read();
// b may be 0 for success,
// 1 for error,
// 2 for fatal error,
// -1
if(b==0) return b;
if(b==-1) return b;
if(b==1 || b==2){
StringBuffer sb=new StringBuffer();
int c;
do {
c=in.read();
sb.append((char)c);
}
while(c!='\n');
if(b==1){ // error
System.out.print(sb.toString());
}
if(b==2){ // fatal error
System.out.print(sb.toString());
}
}
return b;
}
public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{
public String getPassword(){ return passwd; }
public boolean promptYesNo(String str){
Object[] options={ "yes", "no" };
int foo=JOptionPane.showOptionDialog(null,
str,
"Warning",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE,
null, options, options[0]);
return foo==0;
}
String passwd;
JTextField passwordField=(JTextField)new JPasswordField(20);
public String getPassphrase(){ return null; }
public boolean promptPassphrase(String message){ return true; }
public boolean promptPassword(String message){
Object[] ob={passwordField};
int result=
JOptionPane.showConfirmDialog(null, ob, message,
JOptionPane.OK_CANCEL_OPTION);
if(result==JOptionPane.OK_OPTION){
passwd=passwordField.getText();
return true;
}
else{ return false; }
}
public void showMessage(String message){
JOptionPane.showMessageDialog(null, message);
}
final GridBagConstraints gbc =
new GridBagConstraints(0,0,1,1,1,1,
GridBagConstraints.NORTHWEST,
GridBagConstraints.NONE,
new Insets(0,0,0,0),0,0);
private Container panel;
public String[] promptKeyboardInteractive(String destination,
String name,
String instruction,
String[] prompt,
boolean[] echo){
panel = new JPanel();
panel.setLayout(new GridBagLayout());
gbc.weightx = 1.0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.gridx = 0;
panel.add(new JLabel(instruction), gbc);
gbc.gridy++;
gbc.gridwidth = GridBagConstraints.RELATIVE;
JTextField[] texts=new JTextField[prompt.length];
for(int i=0; i<prompt.length; i++){
gbc.fill = GridBagConstraints.NONE;
gbc.gridx = 0;
gbc.weightx = 1;
panel.add(new JLabel(prompt[i]),gbc);
gbc.gridx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weighty = 1;
if(echo[i]){
texts[i]=new JTextField(20);
}
else{
texts[i]=new JPasswordField(20);
}
panel.add(texts[i], gbc);
gbc.gridy++;
}
if(JOptionPane.showConfirmDialog(null, panel,
destination+": "+name,
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE)
==JOptionPane.OK_OPTION){
String[] response=new String[prompt.length];
for(int i=0; i<prompt.length; i++){
response[i]=texts[i].getText();
}
return response;
}
else{
return null; // cancel
}
}
}
}
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/**
* This program will demonstrate the file transfer from local to remote.
* $ CLASSPATH=.:../build javac ScpTo.java
* $ CLASSPATH=.:../build java ScpTo file1 user@remotehost:file2
* You will be asked passwd.
* If everything works fine, a local file 'file1' will copied to
* 'file2' on 'remotehost'.
*
*/
import com.jcraft.jsch.*;
import java.awt.*;
import javax.swing.*;
import java.io.*;
public class ScpTo{
public static void main(String[] arg){
if(arg.length!=2){
System.err.println("usage: java ScpTo file1 user@remotehost:file2");
System.exit(-1);
}
FileInputStream fis=null;
try{
String lfile=arg[0];
String user=arg[1].substring(0, arg[1].indexOf('@'));
arg[1]=arg[1].substring(arg[1].indexOf('@')+1);
String host=arg[1].substring(0, arg[1].indexOf(':'));
String rfile=arg[1].substring(arg[1].indexOf(':')+1);
JSch jsch=new JSch();
Session session=jsch.getSession(user, host, 22);
// username and password will be given via UserInfo interface.
UserInfo ui=new MyUserInfo();
session.setUserInfo(ui);
session.connect();
boolean ptimestamp = true;
// exec 'scp -t rfile' remotely
String command="scp " + (ptimestamp ? "-p" :"") +" -t "+rfile;
Channel channel=session.openChannel("exec");
((ChannelExec)channel).setCommand(command);
// get I/O streams for remote scp
OutputStream out=channel.getOutputStream();
InputStream in=channel.getInputStream();
channel.connect();
if(checkAck(in)!=0){
System.exit(0);
}
File _lfile = new File(lfile);
if(ptimestamp){
command="T "+(_lfile.lastModified()/1000)+" 0";
// The access time should be sent here,
// but it is not accessible with JavaAPI ;-<
command+=(" "+(_lfile.lastModified()/1000)+" 0\n");
out.write(command.getBytes()); out.flush();
if(checkAck(in)!=0){
System.exit(0);
}
}
// send "C0644 filesize filename", where filename should not include '/'
long filesize=_lfile.length();
command="C0644 "+filesize+" ";
if(lfile.lastIndexOf('/')>0){
command+=lfile.substring(lfile.lastIndexOf('/')+1);
}
else{
command+=lfile;
}
command+="\n";
out.write(command.getBytes()); out.flush();
if(checkAck(in)!=0){
System.exit(0);
}
// send a content of lfile
fis=new FileInputStream(lfile);
byte[] buf=new byte[1024];
while(true){
int len=fis.read(buf, 0, buf.length);
if(len<=0) break;
out.write(buf, 0, len); //out.flush();
}
fis.close();
fis=null;
// send '\0'
buf[0]=0; out.write(buf, 0, 1); out.flush();
if(checkAck(in)!=0){
System.exit(0);
}
out.close();
channel.disconnect();
session.disconnect();
System.exit(0);
}
catch(Exception e){
System.out.println(e);
try{if(fis!=null)fis.close();}catch(Exception ee){}
}
}
static int checkAck(InputStream in) throws IOException{
int b=in.read();
// b may be 0 for success,
// 1 for error,
// 2 for fatal error,
// -1
if(b==0) return b;
if(b==-1) return b;
if(b==1 || b==2){
StringBuffer sb=new StringBuffer();
int c;
do {
c=in.read();
sb.append((char)c);
}
while(c!='\n');
if(b==1){ // error
System.out.print(sb.toString());
}
if(b==2){ // fatal error
System.out.print(sb.toString());
}
}
return b;
}
public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{
public String getPassword(){ return passwd; }
public boolean promptYesNo(String str){
Object[] options={ "yes", "no" };
int foo=JOptionPane.showOptionDialog(null,
str,
"Warning",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE,
null, options, options[0]);
return foo==0;
}
String passwd;
JTextField passwordField=(JTextField)new JPasswordField(20);
public String getPassphrase(){ return null; }
public boolean promptPassphrase(String message){ return true; }
public boolean promptPassword(String message){
Object[] ob={passwordField};
int result=
JOptionPane.showConfirmDialog(null, ob, message,
JOptionPane.OK_CANCEL_OPTION);
if(result==JOptionPane.OK_OPTION){
passwd=passwordField.getText();
return true;
}
else{ return false; }
}
public void showMessage(String message){
JOptionPane.showMessageDialog(null, message);
}
final GridBagConstraints gbc =
new GridBagConstraints(0,0,1,1,1,1,
GridBagConstraints.NORTHWEST,
GridBagConstraints.NONE,
new Insets(0,0,0,0),0,0);
private Container panel;
public String[] promptKeyboardInteractive(String destination,
String name,
String instruction,
String[] prompt,
boolean[] echo){
panel = new JPanel();
panel.setLayout(new GridBagLayout());
gbc.weightx = 1.0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.gridx = 0;
panel.add(new JLabel(instruction), gbc);
gbc.gridy++;
gbc.gridwidth = GridBagConstraints.RELATIVE;
JTextField[] texts=new JTextField[prompt.length];
for(int i=0; i<prompt.length; i++){
gbc.fill = GridBagConstraints.NONE;
gbc.gridx = 0;
gbc.weightx = 1;
panel.add(new JLabel(prompt[i]),gbc);
gbc.gridx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weighty = 1;
if(echo[i]){
texts[i]=new JTextField(20);
}
else{
texts[i]=new JPasswordField(20);
}
panel.add(texts[i], gbc);
gbc.gridy++;
}
if(JOptionPane.showConfirmDialog(null, panel,
destination+": "+name,
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE)
==JOptionPane.OK_OPTION){
String[] response=new String[prompt.length];
for(int i=0; i<prompt.length; i++){
response[i]=texts[i].getText();
}
return response;
}
else{
return null; // cancel
}
}
}
}
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/**
* This program will demonstrate how to enable none cipher.
*
*/
import com.jcraft.jsch.*;
import java.awt.*;
import javax.swing.*;
import java.io.*;
public class ScpToNoneCipher{
public static void main(String[] arg){
if(arg.length!=2){
System.err.println("usage: java ScpTo file1 user@remotehost:file2");
System.exit(-1);
}
FileInputStream fis=null;
try{
String lfile=arg[0];
String user=arg[1].substring(0, arg[1].indexOf('@'));
arg[1]=arg[1].substring(arg[1].indexOf('@')+1);
String host=arg[1].substring(0, arg[1].indexOf(':'));
String rfile=arg[1].substring(arg[1].indexOf(':')+1);
JSch jsch=new JSch();
Session session=jsch.getSession(user, host, 22);
// username and password will be given via UserInfo interface.
UserInfo ui=new MyUserInfo();
session.setUserInfo(ui);
session.connect();
session.setConfig("cipher.s2c", "none,aes128-cbc,3des-cbc,blowfish-cbc");
session.setConfig("cipher.c2s", "none,aes128-cbc,3des-cbc,blowfish-cbc");
session.rekey();
// exec 'scp -t rfile' remotely
String command="scp -p -t "+rfile;
Channel channel=session.openChannel("exec");
((ChannelExec)channel).setCommand(command);
// get I/O streams for remote scp
OutputStream out=channel.getOutputStream();
InputStream in=channel.getInputStream();
channel.connect();
if(checkAck(in)!=0){
System.exit(0);
}
// send "C0644 filesize filename", where filename should not include '/'
long filesize=(new File(lfile)).length();
command="C0644 "+filesize+" ";
if(lfile.lastIndexOf('/')>0){
command+=lfile.substring(lfile.lastIndexOf('/')+1);
}
else{
command+=lfile;
}
command+="\n";
out.write(command.getBytes()); out.flush();
if(checkAck(in)!=0){
System.exit(0);
}
// send a content of lfile
fis=new FileInputStream(lfile);
byte[] buf=new byte[1024];
while(true){
int len=fis.read(buf, 0, buf.length);
if(len<=0) break;
out.write(buf, 0, len); out.flush();
}
fis.close();
fis=null;
// send '\0'
buf[0]=0; out.write(buf, 0, 1); out.flush();
if(checkAck(in)!=0){
System.exit(0);
}
session.disconnect();
System.exit(0);
}
catch(Exception e){
System.out.println(e);
try{if(fis!=null)fis.close();}catch(Exception ee){}
}
}
static int checkAck(InputStream in) throws IOException{
int b=in.read();
// b may be 0 for success,
// 1 for error,
// 2 for fatal error,
// -1
if(b==0) return b;
if(b==-1) return b;
if(b==1 || b==2){
StringBuffer sb=new StringBuffer();
int c;
do {
c=in.read();
sb.append((char)c);
}
while(c!='\n');
if(b==1){ // error
System.out.print(sb.toString());
}
if(b==2){ // fatal error
System.out.print(sb.toString());
}
}
return b;
}
public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{
public String getPassword(){ return passwd; }
public boolean promptYesNo(String str){
Object[] options={ "yes", "no" };
int foo=JOptionPane.showOptionDialog(null,
str,
"Warning",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE,
null, options, options[0]);
return foo==0;
}
String passwd;
JTextField passwordField=(JTextField)new JPasswordField(20);
public String getPassphrase(){ return null; }
public boolean promptPassphrase(String message){ return true; }
public boolean promptPassword(String message){
Object[] ob={passwordField};
int result=
JOptionPane.showConfirmDialog(null, ob, message,
JOptionPane.OK_CANCEL_OPTION);
if(result==JOptionPane.OK_OPTION){
passwd=passwordField.getText();
return true;
}
else{ return false; }
}
public void showMessage(String message){
JOptionPane.showMessageDialog(null, message);
}
final GridBagConstraints gbc =
new GridBagConstraints(0,0,1,1,1,1,
GridBagConstraints.NORTHWEST,
GridBagConstraints.NONE,
new Insets(0,0,0,0),0,0);
private Container panel;
public String[] promptKeyboardInteractive(String destination,
String name,
String instruction,
String[] prompt,
boolean[] echo){
panel = new JPanel();
panel.setLayout(new GridBagLayout());
gbc.weightx = 1.0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.gridx = 0;
panel.add(new JLabel(instruction), gbc);
gbc.gridy++;
gbc.gridwidth = GridBagConstraints.RELATIVE;
JTextField[] texts=new JTextField[prompt.length];
for(int i=0; i<prompt.length; i++){
gbc.fill = GridBagConstraints.NONE;
gbc.gridx = 0;
gbc.weightx = 1;
panel.add(new JLabel(prompt[i]),gbc);
gbc.gridx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weighty = 1;
if(echo[i]){
texts[i]=new JTextField(20);
}
else{
texts[i]=new JPasswordField(20);
}
panel.add(texts[i], gbc);
gbc.gridy++;
}
if(JOptionPane.showConfirmDialog(null, panel,
destination+": "+name,
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE)
==JOptionPane.OK_OPTION){
String[] response=new String[prompt.length];
for(int i=0; i<prompt.length; i++){
response[i]=texts[i].getText();
}
return response;
}
else{
return null; // cancel
}
}
}
}
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/**
* This program will demonstrate the sftp protocol support.
* $ CLASSPATH=.:../build javac Sftp.java
* $ CLASSPATH=.:../build java Sftp
* You will be asked username, host and passwd.
* If everything works fine, you will get a prompt 'sftp>'.
* 'help' command will show available command.
* In current implementation, the destination path for 'get' and 'put'
* commands must be a file, not a directory.
*
*/
import com.jcraft.jsch.*;
import java.awt.*;
import javax.swing.*;
public class Sftp{
public static void main(String[] arg){
try{
JSch jsch=new JSch();
String host=null;
if(arg.length>0){
host=arg[0];
}
else{
host=JOptionPane.showInputDialog("Enter username@hostname",
System.getProperty("user.name")+
"@localhost");
}
String user=host.substring(0, host.indexOf('@'));
host=host.substring(host.indexOf('@')+1);
int port=22;
Session session=jsch.getSession(user, host, port);
// username and password will be given via UserInfo interface.
UserInfo ui=new MyUserInfo();
session.setUserInfo(ui);
session.connect();
Channel channel=session.openChannel("sftp");
channel.connect();
ChannelSftp c=(ChannelSftp)channel;
java.io.InputStream in=System.in;
java.io.PrintStream out=System.out;
java.util.Vector cmds=new java.util.Vector();
byte[] buf=new byte[1024];
int i;
String str;
int level=0;
while(true){
out.print("sftp> ");
cmds.removeAllElements();
i=in.read(buf, 0, 1024);
if(i<=0)break;
i--;
if(i>0 && buf[i-1]==0x0d)i--;
//str=new String(buf, 0, i);
//System.out.println("|"+str+"|");
int s=0;
for(int ii=0; ii<i; ii++){
if(buf[ii]==' '){
if(ii-s>0){ cmds.addElement(new String(buf, s, ii-s)); }
while(ii<i){if(buf[ii]!=' ')break; ii++;}
s=ii;
}
}
if(s<i){ cmds.addElement(new String(buf, s, i-s)); }
if(cmds.size()==0)continue;
String cmd=(String)cmds.elementAt(0);
if(cmd.equals("quit")){
c.quit();
break;
}
if(cmd.equals("exit")){
c.exit();
break;
}
if(cmd.equals("rekey")){
session.rekey();
continue;
}
if(cmd.equals("compression")){
if(cmds.size()<2){
out.println("compression level: "+level);
continue;
}
try{
level=Integer.parseInt((String)cmds.elementAt(1));
if(level==0){
session.setConfig("compression.s2c", "none");
session.setConfig("compression.c2s", "none");
}
else{
session.setConfig("compression.s2c", "zlib@openssh.com,zlib,none");
session.setConfig("compression.c2s", "zlib@openssh.com,zlib,none");
}
}
catch(Exception e){}
session.rekey();
continue;
}
if(cmd.equals("cd") || cmd.equals("lcd")){
if(cmds.size()<2) continue;
String path=(String)cmds.elementAt(1);
try{
if(cmd.equals("cd")) c.cd(path);
else c.lcd(path);
}
catch(SftpException e){
System.out.println(e.toString());
}
continue;
}
if(cmd.equals("rm") || cmd.equals("rmdir") || cmd.equals("mkdir")){
if(cmds.size()<2) continue;
String path=(String)cmds.elementAt(1);
try{
if(cmd.equals("rm")) c.rm(path);
else if(cmd.equals("rmdir")) c.rmdir(path);
else c.mkdir(path);
}
catch(SftpException e){
System.out.println(e.toString());
}
continue;
}
if(cmd.equals("chgrp") || cmd.equals("chown") || cmd.equals("chmod")){
if(cmds.size()!=3) continue;
String path=(String)cmds.elementAt(2);
int foo=0;
if(cmd.equals("chmod")){
byte[] bar=((String)cmds.elementAt(1)).getBytes();
int k;
for(int j=0; j<bar.length; j++){
k=bar[j];
if(k<'0'||k>'7'){foo=-1; break;}
foo<<=3;
foo|=(k-'0');
}
if(foo==-1)continue;
}
else{
try{foo=Integer.parseInt((String)cmds.elementAt(1));}
catch(Exception e){continue;}
}
try{
if(cmd.equals("chgrp")){ c.chgrp(foo, path); }
else if(cmd.equals("chown")){ c.chown(foo, path); }
else if(cmd.equals("chmod")){ c.chmod(foo, path); }
}
catch(SftpException e){
System.out.println(e.toString());
}
continue;
}
if(cmd.equals("pwd") || cmd.equals("lpwd")){
str=(cmd.equals("pwd")?"Remote":"Local");
str+=" working directory: ";
if(cmd.equals("pwd")) str+=c.pwd();
else str+=c.lpwd();
out.println(str);
continue;
}
if(cmd.equals("ls") || cmd.equals("dir")){
String path=".";
if(cmds.size()==2) path=(String)cmds.elementAt(1);
try{
java.util.Vector vv=c.ls(path);
if(vv!=null){
for(int ii=0; ii<vv.size(); ii++){
// out.println(vv.elementAt(ii).toString());
Object obj=vv.elementAt(ii);
if(obj instanceof com.jcraft.jsch.ChannelSftp.LsEntry){
out.println(((com.jcraft.jsch.ChannelSftp.LsEntry)obj).getLongname());
}
}
}
}
catch(SftpException e){
System.out.println(e.toString());
}
continue;
}
if(cmd.equals("lls") || cmd.equals("ldir")){
String path=".";
if(cmds.size()==2) path=(String)cmds.elementAt(1);
try{
java.io.File file=new java.io.File(path);
if(!file.exists()){
out.println(path+": No such file or directory");
continue;
}
if(file.isDirectory()){
String[] list=file.list();
for(int ii=0; ii<list.length; ii++){
out.println(list[ii]);
}
continue;
}
out.println(path);
}
catch(Exception e){
System.out.println(e);
}
continue;
}
if(cmd.equals("get") ||
cmd.equals("get-resume") || cmd.equals("get-append") ||
cmd.equals("put") ||
cmd.equals("put-resume") || cmd.equals("put-append")
){
if(cmds.size()!=2 && cmds.size()!=3) continue;
String p1=(String)cmds.elementAt(1);
// String p2=p1;
String p2=".";
if(cmds.size()==3)p2=(String)cmds.elementAt(2);
try{
SftpProgressMonitor monitor=new MyProgressMonitor();
if(cmd.startsWith("get")){
int mode=ChannelSftp.OVERWRITE;
if(cmd.equals("get-resume")){ mode=ChannelSftp.RESUME; }
else if(cmd.equals("get-append")){ mode=ChannelSftp.APPEND; }
c.get(p1, p2, monitor, mode);
}
else{
int mode=ChannelSftp.OVERWRITE;
if(cmd.equals("put-resume")){ mode=ChannelSftp.RESUME; }
else if(cmd.equals("put-append")){ mode=ChannelSftp.APPEND; }
c.put(p1, p2, monitor, mode);
}
}
catch(SftpException e){
System.out.println(e.toString());
}
continue;
}
if(cmd.equals("ln") || cmd.equals("symlink") ||
cmd.equals("rename") || cmd.equals("hardlink")){
if(cmds.size()!=3) continue;
String p1=(String)cmds.elementAt(1);
String p2=(String)cmds.elementAt(2);
try{
if(cmd.equals("hardlink")){ c.hardlink(p1, p2); }
else if(cmd.equals("rename")) c.rename(p1, p2);
else c.symlink(p1, p2);
}
catch(SftpException e){
System.out.println(e.toString());
}
continue;
}
if(cmd.equals("df")){
if(cmds.size()>2) continue;
String p1 = cmds.size()==1 ? ".": (String)cmds.elementAt(1);
SftpStatVFS stat = c.statVFS(p1);
long size = stat.getSize();
long used = stat.getUsed();
long avail = stat.getAvailForNonRoot();
long root_avail = stat.getAvail();
long capacity = stat.getCapacity();
System.out.println("Size: "+size);
System.out.println("Used: "+used);
System.out.println("Avail: "+avail);
System.out.println("(root): "+root_avail);
System.out.println("%Capacity: "+capacity);
continue;
}
if(cmd.equals("stat") || cmd.equals("lstat")){
if(cmds.size()!=2) continue;
String p1=(String)cmds.elementAt(1);
SftpATTRS attrs=null;
try{
if(cmd.equals("stat")) attrs=c.stat(p1);
else attrs=c.lstat(p1);
}
catch(SftpException e){
System.out.println(e.toString());
}
if(attrs!=null){
out.println(attrs);
}
else{
}
continue;
}
if(cmd.equals("readlink")){
if(cmds.size()!=2) continue;
String p1=(String)cmds.elementAt(1);
String filename=null;
try{
filename=c.readlink(p1);
out.println(filename);
}
catch(SftpException e){
System.out.println(e.toString());
}
continue;
}
if(cmd.equals("realpath")){
if(cmds.size()!=2) continue;
String p1=(String)cmds.elementAt(1);
String filename=null;
try{
filename=c.realpath(p1);
out.println(filename);
}
catch(SftpException e){
System.out.println(e.toString());
}
continue;
}
if(cmd.equals("version")){
out.println("SFTP protocol version "+c.version());
continue;
}
if(cmd.equals("help") || cmd.equals("?")){
out.println(help);
continue;
}
out.println("unimplemented command: "+cmd);
}
session.disconnect();
}
catch(Exception e){
System.out.println(e);
}
System.exit(0);
}
public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{
public String getPassword(){ return passwd; }
public boolean promptYesNo(String str){
Object[] options={ "yes", "no" };
int foo=JOptionPane.showOptionDialog(null,
str,
"Warning",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE,
null, options, options[0]);
return foo==0;
}
String passwd;
JTextField passwordField=(JTextField)new JPasswordField(20);
public String getPassphrase(){ return null; }
public boolean promptPassphrase(String message){ return true; }
public boolean promptPassword(String message){
Object[] ob={passwordField};
int result=
JOptionPane.showConfirmDialog(null, ob, message,
JOptionPane.OK_CANCEL_OPTION);
if(result==JOptionPane.OK_OPTION){
passwd=passwordField.getText();
return true;
}
else{ return false; }
}
public void showMessage(String message){
JOptionPane.showMessageDialog(null, message);
}
final GridBagConstraints gbc =
new GridBagConstraints(0,0,1,1,1,1,
GridBagConstraints.NORTHWEST,
GridBagConstraints.NONE,
new Insets(0,0,0,0),0,0);
private Container panel;
public String[] promptKeyboardInteractive(String destination,
String name,
String instruction,
String[] prompt,
boolean[] echo){
panel = new JPanel();
panel.setLayout(new GridBagLayout());
gbc.weightx = 1.0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.gridx = 0;
panel.add(new JLabel(instruction), gbc);
gbc.gridy++;
gbc.gridwidth = GridBagConstraints.RELATIVE;
JTextField[] texts=new JTextField[prompt.length];
for(int i=0; i<prompt.length; i++){
gbc.fill = GridBagConstraints.NONE;
gbc.gridx = 0;
gbc.weightx = 1;
panel.add(new JLabel(prompt[i]),gbc);
gbc.gridx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weighty = 1;
if(echo[i]){
texts[i]=new JTextField(20);
}
else{
texts[i]=new JPasswordField(20);
}
panel.add(texts[i], gbc);
gbc.gridy++;
}
if(JOptionPane.showConfirmDialog(null, panel,
destination+": "+name,
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE)
==JOptionPane.OK_OPTION){
String[] response=new String[prompt.length];
for(int i=0; i<prompt.length; i++){
response[i]=texts[i].getText();
}
return response;
}
else{
return null; // cancel
}
}
}
/*
public static class MyProgressMonitor implements com.jcraft.jsch.ProgressMonitor{
JProgressBar progressBar;
JFrame frame;
long count=0;
long max=0;
public void init(String info, long max){
this.max=max;
if(frame==null){
frame=new JFrame();
frame.setSize(200, 20);
progressBar = new JProgressBar();
}
count=0;
frame.setTitle(info);
progressBar.setMaximum((int)max);
progressBar.setMinimum((int)0);
progressBar.setValue((int)count);
progressBar.setStringPainted(true);
JPanel p=new JPanel();
p.add(progressBar);
frame.getContentPane().add(progressBar);
frame.setVisible(true);
System.out.println("!info:"+info+", max="+max+" "+progressBar);
}
public void count(long count){
this.count+=count;
System.out.println("count: "+count);
progressBar.setValue((int)this.count);
}
public void end(){
System.out.println("end");
progressBar.setValue((int)this.max);
frame.setVisible(false);
}
}
*/
public static class MyProgressMonitor implements SftpProgressMonitor{
ProgressMonitor monitor;
long count=0;
long max=0;
public void init(int op, String src, String dest, long max){
this.max=max;
monitor=new ProgressMonitor(null,
((op==SftpProgressMonitor.PUT)?
"put" : "get")+": "+src,
"", 0, (int)max);
count=0;
percent=-1;
monitor.setProgress((int)this.count);
monitor.setMillisToDecideToPopup(1000);
}
private long percent=-1;
public boolean count(long count){
this.count+=count;
if(percent>=this.count*100/max){ return true; }
percent=this.count*100/max;
monitor.setNote("Completed "+this.count+"("+percent+"%) out of "+max+".");
monitor.setProgress((int)this.count);
return !(monitor.isCanceled());
}
public void end(){
monitor.close();
}
}
private static String help =
" Available commands:\n"+
" * means unimplemented command.\n"+
"cd path Change remote directory to 'path'\n"+
"lcd path Change local directory to 'path'\n"+
"chgrp grp path Change group of file 'path' to 'grp'\n"+
"chmod mode path Change permissions of file 'path' to 'mode'\n"+
"chown own path Change owner of file 'path' to 'own'\n"+
"df [path] Display statistics for current directory or\n"+
" filesystem containing 'path'\n"+
"help Display this help text\n"+
"get remote-path [local-path] Download file\n"+
"get-resume remote-path [local-path] Resume to download file.\n"+
"get-append remote-path [local-path] Append remote file to local file\n"+
"hardlink oldpath newpath Hardlink remote file\n"+
"*lls [ls-options [path]] Display local directory listing\n"+
"ln oldpath newpath Symlink remote file\n"+
"*lmkdir path Create local directory\n"+
"lpwd Print local working directory\n"+
"ls [path]