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) {
}
JSch is the Java implementation of SSH2 that allows us to connect to an SSH server and use port forwarding, X11 forwarding, and file transfer. Also, it is licensed under the BSD style license and provides us with an easy way to establish an SSH connection with Java.
addIdentity(String prvkey, String pubkey, byte[] passphrase) Adds an identity to be used for public-key authentication. protected void. addSession(Session session) Adds a session to our session pool.
JSch is a pure Java implementation of SSH2. JSch allows you to connect to an sshd server and use port forwarding, X11 forwarding, file transfer, etc., and you can integrate its functionality into your own Java programs. JSch is licensed under BSD style license.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With