Newsgroup: it.comp.java
Titolo: java lib sftp client

Salve sto cercando una libreria per la connessione sftp, ne ho trovate
2 che però non riesco a far funzionare sul mio computer le librerie
sono: j2ssh e jsch mentre il server ssh è SSH-2.0-OpenSSH_4.2p1 Debian
. Le librerie con gli esempi che hanno in allegato non mi fanno
autenticare :
log j2ssh:
22-giu-2006 23.12.15
com.sshtools.j2ssh.configuration.ConfigurationLoader initialize
INFO: JAVA version is 1.4.2_04
22-giu-2006 23.12.15
com.sshtools.j2ssh.configuration.ConfigurationLoader initialize
INFO: Extension
/home/nemo/Borland/JBuilder2005/jdk1.4/jre/lib/ext/sunjce_provider.jar
being added to classpath
22-giu-2006 23.12.15 com.sshtools.j2ssh.util.ExtensionClassLoader add
INFO: Adding
/home/nemo/Borland/JBuilder2005/jdk1.4/jre/lib/ext/sunjce_provider.jar
to the extension classpath
22-giu-2006 23.12.15
com.sshtools.j2ssh.configuration.ConfigurationLoader initialize
INFO: Extension
/home/nemo/Borland/JBuilder2005/jdk1.4/jre/lib/ext/dnsns.jar being
added to classpath
22-giu-2006 23.12.15 com.sshtools.j2ssh.util.ExtensionClassLoader add
INFO: Adding
/home/nemo/Borland/JBuilder2005/jdk1.4/jre/lib/ext/dnsns.jar to the
extension classpath
22-giu-2006 23.12.15
com.sshtools.j2ssh.configuration.ConfigurationLoader initialize
INFO: Extension
/home/nemo/Borland/JBuilder2005/jdk1.4/jre/lib/ext/ldapsec.jar being
added to classpath
22-giu-2006 23.12.15 com.sshtools.j2ssh.util.ExtensionClassLoader add
INFO: Adding
/home/nemo/Borland/JBuilder2005/jdk1.4/jre/lib/ext/ldapsec.jar to the
extension classpath
22-giu-2006 23.12.15
com.sshtools.j2ssh.configuration.ConfigurationLoader initialize
INFO: Extension
/home/nemo/Borland/JBuilder2005/jdk1.4/jre/lib/ext/localedata.jar being
added to classpath
22-giu-2006 23.12.15 com.sshtools.j2ssh.util.ExtensionClassLoader add
INFO: Adding
/home/nemo/Borland/JBuilder2005/jdk1.4/jre/lib/ext/localedata.jar to
the extension classpath
22-giu-2006 23.12.15
com.sshtools.j2ssh.transport.publickey.SshKeyPairFactory <clinit>
INFO: Loading public key algorithms
22-giu-2006 23.12.15
com.sshtools.j2ssh.transport.cipher.SshCipherFactory <clinit>
INFO: Loading supported cipher algorithms
22-giu-2006 23.12.15
com.sshtools.j2ssh.transport.kex.SshKeyExchangeFactory <clinit>
INFO: Loading key exchange methods
22-giu-2006 23.12.15
com.sshtools.j2ssh.transport.compression.SshCompressionFactory <clinit>
INFO: Loading compression methods
22-giu-2006 23.12.15 com.sshtools.j2ssh.transport.hmac.SshHmacFactory
<clinit>
INFO: Loading message authentication methods
22-giu-2006 23.12.15
com.sshtools.j2ssh.transport.TransportProtocolCommon
startTransportProtocol
INFO: Starting transport protocol
22-giu-2006 23.12.15
com.sshtools.j2ssh.transport.TransportProtocolCommon run
INFO: Registering transport protocol messages with inputstream
Connect to host? 22-giu-2006 23.12.15
com.sshtools.j2ssh.transport.TransportProtocolCommon negotiateVersion
INFO: Negotiating protocol version
22-giu-2006 23.12.15
com.sshtools.j2ssh.transport.TransportProtocolCommon negotiateVersion
INFO: Protocol negotiation complete
22-giu-2006 23.12.15
com.sshtools.j2ssh.transport.TransportProtocolCommon beginKeyExchange
INFO: Starting key exchange
22-giu-2006 23.12.15 com.sshtools.j2ssh.transport.kex.DhGroup1Sha1
performClientExchange
INFO: Starting client side key exchange.
22-giu-2006 23.12.15
com.sshtools.j2ssh.transport.AbstractKnownHostsKeyVerification
verifyHost
INFO: Verifying 192.168.0.147 host key
The host 192.168.0.147 is currently unknown to the system
The host key fingerprint is: 1024: 5c 82 d6 78 fd e7 9 c 25 2e 44 40 5b
93 4e 2b
Do you want to allow this host key? [Yes|No|Always]: yes
22-giu-2006 23.12.21
com.sshtools.j2ssh.transport.TransportProtocolClient verifyHostKey
INFO: The host key signature is  valid
22-giu-2006 23.12.21
com.sshtools.j2ssh.transport.TransportProtocolCommon
completeKeyExchange
INFO: Completing key exchange
22-giu-2006 23.12.21
com.sshtools.j2ssh.transport.cipher.SshCipherFactory newInstance
INFO: Creating new blowfish-cbc cipher instance
22-giu-2006 23.12.21
com.sshtools.j2ssh.transport.cipher.SshCipherFactory newInstance
INFO: Creating new blowfish-cbc cipher instance
Username?
Password?
esco
log  jsch:
com.jcraft.jsch.JSchException: Auth fail
Avete qualche idea ??
Grazie mille

 Grazie mille
Io la seconda la uso senza problemi.
Quelo che e' strano e' che ti dovrebbe chiedere anche se vuoi
utilizzare il certificato.
Necessito ulteriori input
avana0101


 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public License
 * as published by the Free Software Foundation; either version 2 of
 * the License, or (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */
import java.io.BufferedReader;
import java.io.InputStreamReader;
import com.sshtools.j2ssh.SshClient;
import com.sshtools.j2ssh.authentication.AuthenticationProtocolState;
import com.sshtools.j2ssh.authentication.PasswordAuthenticationClient;
import com.sshtools.j2ssh.io.UnsignedInteger32;
import com.sshtools.j2ssh.session.SessionChannelClient;
import com.sshtools.j2ssh.sftp.FileAttributes;
import com.sshtools.j2ssh.sftp.SftpFile;
import com.sshtools.j2ssh.sftp.SftpFileOutputStream;
import com.sshtools.j2ssh.SftpClient;
import java.io.*;
import com.sshtools.j2ssh.configuration.ConfigurationLoader;
/*import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;*/
/**
 * Demonstrates a simple password connection to an SSH server.
 *
 * @author <A HREF="mailto:
l...@sshtools.com
">Lee David Painter</A>
 * @version $Id: SftpConnect.java,v 1.8 2003/07/16 10:42:08
t_magicthize Exp $
 *
 * @created 20 December 2002
 */
public class SftpConnect {
  /**
   * The main program for the PasswordConnect class
   *
   * @param args The command line arguments
   */
  public static void main(String args[]) {
    try {
      // Setup a logfile
      /*Handler fh = new FileHandler("example.log");
      fh.setFormatter(new SimpleFormatter());
      Logger.getLogger("com.sshtools").setUseParentHandlers(false);
      Logger.getLogger("com.sshtools").addHandler(fh);
      Logger.getLogger("com.sshtools").setLevel(Level.ALL);*/
      // Configure J2SSH (This will attempt to install the bouncycastle
provider
      // under jdk 1.3.1)
      ConfigurationLoader.initialize(false);
      BufferedReader reader =
          new BufferedReader(new InputStreamReader(System.in));
      System.out.print("Connect to host? ");
      String hostname = "192.168.0.147";//reader.readLine();
      // Make a client connection
      SshClient ssh = new SshClient();
      // Connect to the host
      ssh.connect(hostname,22);
      // Create a password authentication instance
      PasswordAuthenticationClient pwd = new
PasswordAuthenticationClient();
      // Get the users name
      System.out.print("Username? ");
      String username = "username";//reader.readLine();
      pwd.setUsername(username);
      // Get the password
      System.out.print("Password? ");
      String password = "password";//reader.readLine();
      pwd.setPassword(password);
      // Try the authentication
      int result = ssh.authenticate(pwd);
      // Evaluate the result
      if (result == AuthenticationProtocolState.COMPLETE) {
        // The connection is authenticated we can now do some real
work!
        SftpClient sftp = ssh.openSftpClient();
        // Make a directory
        try {
          sftp.mkdir("j2ssh");
        }
        catch (IOException ex) {
        }
        // Change directory
 
sftp.cd
("j2ssh");
        System.out.println(sftp.pwd());
        // Change the mode
        sftp.chmod(0777, "j2ssh");
        sftp.lcd("c:/");
        // Upload a file
        sftp.put("system.gif");
        // Change the local directory
        sftp.lcd("localdir");
        // Download a file
        sftp.get("somefile.txt", "anotherfile.txt");
        // Remove a directory or file
        sftp.rm("j2ssh");
        // Quit
        sftp.quit();
        ssh.disconnect();
      }
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    finally {
    	System.out.print("esco");
      System.exit(0);
    }
  }
}
questo esempio non funziona non riesce ad autenticarsi, invece con
altri client (esempio filezilla) riesco a connettermi.
Grazie
avan...@yahoo.it
 ha scritto:


nemo ha scritto:

Bisognerebe vedere la funzione di connessione come funziona
Comunque se ti scarichi jar ed esempi da questo indirizzo
http://www.jcraft.com/jsch/
vai tranquillo!!!
ciao 
avana01

ho provato anche quella libreria ecco l'esempio che ho eseguito :
package nemo.test;
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
import com.jcraft.jsch.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
public class NemoSftp {
public static int exec (String cmd,Session session,Channel channel) {
return exec (cmd,session,channel,true);
}
public static int exec (String cmd,Session session,Channel
channel,boolean ret_str) {
int i = -1;
try{
channel=session.openChannel("exec");
((ChannelExec)channel).setCommand(cmd);
channel.setInputStream(System.in);
((ChannelExec)channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
System.out.println("cmd == " + cmd +
"............................................");
channel.connect();
if (channel.isConnected() == false) {
System.out.println("<------------------------->");
}
/*
try {
Thread.sleep(500);
} catch (InterruptedException e) { }
*/
if (ret_str) {
byte[] tmp=new byte[1024];
while(true){
while(in.available()>0){
i=in.read(tmp, 0, 1024);
if(i<0){
System.out.print("Sink me!");
break;
}
System.out.print(new String(tmp, 0, i));
}
if(channel.isClosed()){
System.out.println("exit-status: "+channel.getExitStatus());
System.out.println("<==>" + i);
break;
}
}
}
else {
i = 0;
}
}
catch(Exception e){
System.out.println(e);
}
return i;
}
public static void main(String[] arg){
try{
JSch jsch=new JSch();
String host = "127.0.0.1";
String user = "nemo";
String pass = "";
Session session=jsch.getSession(user, host, 22);
// username and password will be given via UserInfo interface.
UserInfo ui=new MyUserInfo();
((MyUserInfo)ui).setPassword(pass);
//session.setPassword(pass);
session.setUserInfo(ui);
session.connect();
// and away we goooooo!
int retc = -1;
Channel channel=session.openChannel("exec");
while (true) {
retc = exec ("top -n 1 -b",session,channel);
if (retc != -1) break;
}
while (true) {
retc = exec ("echo gieyo_gieyo_gieyo >
/tmp/one_piece",session,channel,false);
if (retc != -1) break;
}
while (true) {
retc = exec ("cp /tmp/bigfile /tmp/bigfilecp",session,channel,false);
if (retc != -1) break;
}
 l'errore che mi da è "Auth Fail"
channel.disconnect();
session.disconnect();
System.exit(0);
}
catch(Exception e){
System.out.println(e);
}
}
public static class MyUserInfo implements UserInfo {
public String pwd;
public void setPassword (String pass) {pwd = pass;}
public String getPassword(){ return pwd; }
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;
}
JTextField passwordField=(JTextField)new JPasswordField(20);
public String getPassphrase(){ return null; }
public boolean promptPassphrase(String message){ return true; }
public boolean promptPassword(String message){
return true;
}
public void showMessage(String message){
//JOptionPane.showMessageDialog(null, message);
}
}
}
avan...@yahoo.it
 ha scritto:


Non so cosa dirti, a me funziona.
Ma se ti butta fuori il server, hai provato a leggere il log?
Dovrebbe aiutarti a capire per quale motivo ti butta fuori.
Suppongo che tu abbia creato la home per l'account sul server! No?
avana01

ma tu che server ssh usi ??
ci deve essere qualcosa che non va sul mio server ssh (Open ssh), ma
allora perchè funziona con filezilla, cygwin.
Continuo ad indagare, se tiviene in mente qualcosa fammi sapere .
Grazie
avan...@yahoo.it
 ha scritto:


Ecco il log sshd :
debug1: rexec_argv[2]='-d'
debug1: rexec_argv[3]='-p'
debug1: rexec_argv[4]='22'
debug2: fd 3 setting O_NONBLOCK
debug1: Bind to port 22 on ::.
Server listening on :: port 22.
debug2: fd 4 setting O_NONBLOCK
debug1: Bind to port 22 on 0.0.0.0.
debug1: Server will not fork when running in debugging mode.
debug1: rexec start in 4 out 4 newsock 4 pipe -1 sock 7
debug1: inetd sockets after dupping: 3, 3
Connection from 10.3.25.35 port 2985
debug1: Client protocol version 2.0; client software version
http://www.sshtools
.com J2SSH [CLIENT]
debug1: no match: 
http://www.sshtools.com
 J2SSH [CLIENT]
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_4.2p1 Debian-5
debug2: fd 3 setting O_NONBLOCK
debug1: permanently_set_uid: 101/65534
debug1: list_hostkey_types: ssh-rsa,ssh-dss
debug2: Network child is on pid 6464
debug1: Miscellaneous failure
No such file or directory
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug2: kex_parse_kexinit:
diffie-hellman-group-exchange-sha1,diffie-hellman-gro
up14-sha1,diffie-hellman-group1-sha1
debug2: kex_parse_kexinit: ssh-rsa,ssh-dss
debug2: kex_parse_kexinit:
aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour1
28,arcfour256,arcfour,aes192-cbc,aes256-cbc,
rijnda...@lysator.liu.se
,aes128-c
tr,aes192-ctr,aes256-ctr
debug2: kex_parse_kexinit:
aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour1
28,arcfour256,arcfour,aes192-cbc,aes256-cbc,
rijnda...@lysator.liu.se
,aes128-c
tr,aes192-ctr,aes256-ctr
debug2: kex_parse_kexinit:
hmac-md5,hmac-sha1,hmac-ripemd160,hmac-ripemd160@open
ssh.com
,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit:
hmac-md5,hmac-sha1,hmac-ripemd160,hmac-ripemd160@open
ssh.com
,hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: none,
zl...@openssh.com
debug2: kex_parse_kexinit: none,
zl...@openssh.com
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit: first_kex_follows 0
debug2: kex_parse_kexinit: reserved 0
debug2: kex_parse_kexinit: diffie-hellman-group1-sha1
debug2: kex_parse_kexinit: ssh-rsa,ssh-dss
debug2: kex_parse_kexinit: 3des-cbc,blowfish-cbc
debug2: kex_parse_kexinit: 3des-cbc,blowfish-cbc
debug2: kex_parse_kexinit: hmac-sha1,hmac-md5-96,hmac-md5,hmac-sha1-96
debug2: kex_parse_kexinit: hmac-sha1,hmac-md5-96,hmac-md5,hmac-sha1-96
debug2: kex_parse_kexinit: none
debug2: kex_parse_kexinit: none
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit: first_kex_follows 0
debug2: kex_parse_kexinit: reserved 0
debug2: mac_init: found hmac-sha1
debug1: kex: client->server 3des-cbc hmac-sha1 none
debug2: mac_init: found hmac-sha1
debug1: kex: server->client 3des-cbc hmac-sha1 none
debug2: dh_gen_key: priv key bits set: 207/384
debug2: bits set: 509/1024
debug1: expecting SSH2_MSG_KEXDH_INIT
debug2: bits set: 507/1024
debug2: monitor_read: 4 used once, disabling now
debug2: kex_derive_keys
debug2: set_newkeys: mode 1
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug2: set_newkeys: mode 0
debug1: SSH2_MSG_NEWKEYS received
debug1: KEX done
debug1: userauth-request for user root service ssh-connection method
password
debug1: attempt 0 failures 0
debug2: input_userauth_request: setting up authctxt for root
debug2: Unrecognized authentication method name: password
Failed password for root from 10.3.25.35 port 2985 ssh2
debug2: monitor_read: 6 used once, disabling now
debug1: PAM: initializing for "root"
debug1: PAM: setting PAM_RHOST to "nemohost"
debug1: PAM: setting PAM_TTY to "ssh"
debug2: monitor_read: 47 used once, disabling now
debug2: monitor_read: 3 used once, disabling now
avan...@yahoo.it
 ha scritto:


 autenticare :
La butto li senza aver guardato come fai a collegarti e quale tipo di
libreria usi, ma visto che molti ci cascano...
hai disabilitato la verifica della chiave?
Ciao,
Cristian. 

Era prorio quello ti ringrazio
# Change to yes to enable tunnelled clear text passwords
#PasswordAuthentication no
PasswordAuthentication yes
lo scrivo per i posteri .
sai se è possibile autenticarsi con il parametro impostato a no
Grazie
crx ha scritto:


crx ha scritto:

Non c'e' bisogno di disabilitare la verifica della chiave,
OpenSSH ti chiede nel caso di chiave non verificata, se vuoi accedere o
meno
Forse c'e' qualche problema nell'installazione del server OpenSSH,
prova a rifarla da capo
avana01

 meno
Esatto ma il client java non e' interattivo quindi, lato cliente, e'
necessario mettere in "trust" la richiesta.
Cmq, mi sembra che abbia risolto facendo come ho detto ;)
Ciao,
crx.

 sai se è possibile autenticarsi con il parametro impostato a no
Cavoli stavo letteralmente cazzeggiando per i vecchi post e ho ritrovato
questo che non avevo letto bene dove mi facevi la domanda :S
Ritardo mostruoso :) ma puo servire a qualcun'altro, sicuramente tu hai
gia' risolto.
Con quello che ti avevo scrito non intendevo dire che dovevi modificare la
configurazione sshd ma dovevi fare in questo modo(almeno con le j2ssh):
SshClient ssh = new SshClient();
ssh.connect("iltuohost", new IgnoreHostKeyVerification()); 
Ciao,
Cristian.