10

I want to upload a file to a remote server via sftp. I am using the Jsch library. The code below works, but I always have to enter the username and password via the output console, even though I've set those values in the Session object. Every example I've seen on Stack Overflow and on the Jsch example page requires user input. Is there a way to pass the password programmatically? (I am required to authenticate via username/password. I cannot use SSH keys...)

    JSch jsch = new JSch();
    ChannelSftp sftpChannel;
    Session session;
    Channel channel;
    OutputStream os;

    try {

        session = jsch.getSession("myUsername", "myHost", 22);
        session.setPassword("myPassword");
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect();

        channel = session.openChannel("sftp");
        channel.connect();
        sftpChannel = (ChannelSftp) channel;
        os = sftpChannel.getOutputStream();

    } catch (Exception e) {
    }
Ted
  • 1,641
  • 7
  • 30
  • 52
  • I am not sure you still need this to answer. After longer hours I found something useful. please follow the link "https://stackoverflow.com/a/47290119/1376581". But, you should be careful while passing password directly in your code. The jar and example code will help you to run ssh commands automatically through code and no user prompt appears. – MKod Nov 14 '17 at 16:07
  • Did you read this topic: https://stackoverflow.com/questions/5561862/userinfo-passing-yes-click-to-function – stan Sep 16 '13 at 19:59
  • 1
    the code in the link you provided did not automatically pass the credentials to the host server. The user is still prompted to authenticate... – Ted Sep 17 '13 at 13:33
  • What if you change the "promptYesNo()" method to return false instead of true (in SftpUserInfo class) – stan Sep 17 '13 at 14:45

2 Answers2

4

You need to add the below codes :

jsch.addIdentity("<Key_path>"); // replace the key_path with actual value
session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");

Thanks

Rajiv Kumar
  • 194
  • 9
1

You can set up a factory with username and password and use that to create your session:

    final DefaultSftpSessionFactory factory = new DefaultSftpSessionFactory(true);
    factory.setHost(...);
    factory.setPort(...);
    factory.setUser(..);
    factory.setPassword(...);
    factory.setAllowUnknownKeys(true);
    final Session session = factory.getSession();

Take a look at Spring Integration, they have abstracted ftp into a messaging gateway which is quite nice (not going into more detail here as it's not directly related to the question)

Markoorn
  • 2,477
  • 1
  • 16
  • 31