I am using JSch in a Java client to connect to a remote server and get some files using SFTP. The following code has been working fine for me: -
JSch ssh = new JSch();
JSch.setConfig(FileTransferConstants.STRICT_HOST_KEY_CHECKING, FileTransferConstants.NO);
Session session = ssh.getSession(userName, host, port);
session.setPassword(password);
session.connect();
Channel channel = session.openChannel(FileTransferConstants.SFTP);
channel.connect();
ChannelSftp sftp = (ChannelSftp) channel;
sftp.cd(remoteDirectoryPath);
sftp.lcd(localDirectoryPath);
sftp.get(remoteDirectoryPath + remoteFileName, remoteFileName);
The problem is that there has now been a change of site policy. I am no longer permitted to log on directly as this user (userName above). I must first log on as my personal user and then su into the user that has access to the files I want to SFTP.
I don't think there is anyway I can refactor the above code to achieve this and so I have started looking at using a shell or exec channel instead. I have had little success so far and cannot seem to find any examples on the web, so I would be very grateful for any advice or pointers in the right direction. Many thanks.
I do not think you can do this directly with JSch. But with some modification of its code, it's probably doable.
Note that my answer assumes that the server is *nix-based (what is backed by your reference to su) and uses OpenSSH SFTP server.
You have to open SSH "exec" channel, to execute something like:
sudo /bin/sftp-server
But on top of that channel, you need to build the ChannelSftp instance, not ChannelExec.
So you will need to implement Session.openChannel-like method, that will open exec channel, but create ChannelSftp for it.
For some background, see how it's possible to do sudo with WinSCP SFTP client.
Note that while the FAQ claims, that you won't be able to use password for the sudo, that's true for WinSCP. But as you have a full control of the session with JSch, you may be able to feed the password to sudo.
For that you might override the ChannelSftp.start() to write the password to the channel input, before starting the actual SFTP session.
You still need the requiretty option be off, as the SFTP cannot work with TTY.
For general considerations when automating operations using a different/root account, see:
Allowing automatic command execution as root on Linux using SSH
Related
In our project, we need to get a file from external SFTP server using public key authentication. I have searched online but didn't any example for mentioning proxy server routing since it's required as per company's policy
We are using the following command on Unix server to get the file but we want to use java program to implement this functionality
sftp -v -oIdentityFile=/home/intusr/.ssh/id_rsa -oProxyCommand="/usr/bin/corkscrew 11.555.66.22 4444 %h %p" user#transmit.com:stage/filedir/
Your help will be appreciated. Best resource I have found so far is
https://kodehelp.com/java-program-for-uploading-file-to-sftp-server/
The most commonly used Java SSH library is JSch, which supports both public key authentication and HTTP proxy:
How to transfer a file using a proxy with JSch library
Can we use JSch for SSH key-based communication?
Combined, the code would be like:
JSch jsch = new JSch();
jsch.addIdentity("/path/to/private/key");
Session session = jsch.getSession("user", "host");
ProxyHTTP proxy = new ProxyHTTP("proxy", proxyport)
proxy.setUserPasswd("proxyusername", "proxypassword");
session.setProxy(proxy);
session.connect();
For downloading a file, see:
How to retrieve a file from a server via SFTP?
You will have to verify server host key as well.
I have a Spring Boot program that runs in a server, and it needs to read file from a different machine (Both machines are Windows OS). In the remote machine, I do not use any web-server such as apache/nginx - and I don't want to. I want to directly read files from the disk.
What I want is to provide the required params (probably IP, user name and password of the remote host), and a path in the file system - to direct access to the files without web server.
public void readFile(String ip, String userName, String password, String path);
How can I achieve this?
You need to do a scp (which allows copying files from different machines) from Java. This library will help
Also a working example which copies a file from remote to local
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, 22);
...
String command = "scp -f "+rfile;
Channel channel = session.openChannel("exec");
((ChannelExec)channel).setCommand(command);
InputStream in = channel.getInputStream();
channel.connect();
// "in" contains the input stream of the file
You can do something like
activate FTP protocol on the other machine and use java ftp implementations
create a network shared drive and grant access to specific windows users within your domain. you just need to know the network drive url and can access the file as if it was locally
execute a seperate powershell /ssh / scp / ... task from within your java code to open a remote-session and transfer the file
write your own http-server application in java and run on it on the other pc and connect to it as a client
...
I am using the library jsch to make ssh connection. I am useing following code;
JSch jsch = new JSch();
Session session = jsch.getSession("username", "host", port);
But how to put some specific option while I am creating the connection? Actually I want to replicate;
ssh -R abc:8080:localhost80 mysite.com
This command using jsch.
Is it possible using jsch? Or I should use some other library.
Any suggestion will be very helpful.
Thanks in advance.
Is it more options than port forwarding that you need?
Port forwarding (as in -R) is possible with JSch - example here.
If the objective is emulating the OpenSSH command line options, this would be tougher. To the best of my knowledge, all the various SSH libraries for Java, JSch included, focus on providing connectivity for applications that need SSH support. That sounds like it would need a small project in command line parsing.
I wanted to download files using FTP from a server. I can do it properly through command-line and want the same thing using Java. This is my code
session = jsch.getSession(user, server, 22);
session.setPassword(pass);
session.setTimeout(10000);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
**channel.connect();**
channel.disconnect();
session.disconnect();
Problem is when the channel is connecting i.e channel.connect and I am getting an error:
com.jcraft.jsch.JSchException: 4: Received message is too long: 1619214428
at com.jcraft.jsch.ChannelSftp.start(ChannelSftp.java:242)
at com.jcraft.jsch.Channel.connect(Channel.java:200)
at com.jcraft.jsch.Channel.connect(Channel.java:144)
at com.cca.processor.FTPProcessor.main(FTPProcessor.java:54)
Caused by: 4: Received message is too long: 1619214428
at com.jcraft.jsch.ChannelSftp.start(ChannelSftp.java:214)
... 3 more
As you commented yourself, you cannot connect with any SFTP client.
So there's nothing wrong with your JSch/Java code.
The error occurs only after an SSH authentication, when an SFTP session is starting.
It's typically caused by some startup shell script printing a message, and thus breaking the SFTP protocol.
The number in the error (1619214428) is then the first four characters in the message interpreted as a 32-bit number.
But in your case it does not really seem to be a readable text (were it, WinSCP would display the readable form too). The number stands for 6083405C in hexadecimal notation, what is <.(# (where the dot stands for a character outside of ASCII table).
See also WinSCP documentation for the error message:
https://winscp.net/eng/docs/message_large_packet
Still, it's the server that is broken, not your code. You should contact your server administrator or review startup shell scripts of your account.
Though you claim you were able to use FTP from command-line and WinSCP. So maybe you should actually use FTP (or better FTPS), not SFTP. You cannot use JSch for FTP (or FTPS). You can use Apache Commons FTPClient for example.
I am trying to copy some files from a Windows machine to a Linux machine, which is working fine with JSch so far. I can copy files using StrictHostKeyChecking no or I need to have the known_host file from the Linux machine I copy to. I am using the code for a Java project which should be able to send files automatically to (unknown) Linux machines. I got the username, password, IP and the publickey for the machine. Is there any way to authenticate without the known_host file and via the publickey? Because of security issues I do not want to switch StrictHostKeyChecking to no but then I get "com.jcraft.jsch.JSchException: UnknownHostKey"
FileInputStream fis = null;
JSch jsch = new JSch();
//jsch.setKnownHosts("");
jsch.addIdentity("D:\\Uni\\Arbeit\\remote_id_rsa");
Session session=jsch.getSession(user, host, 22);
session.setPassword(password);
//session.setConfig("StrictHostKeyChecking", "no");
session.connect();
That does not make sense. Either you know the host public key and you can verify it either using the known_host file or programmatically using:
public void KnownHosts.add(HostKey hostkey, UserInfo userinfo)
(You can access the instance of KnownHosts using Session.getHostKeyRepository())
For more details, see How to resolve Java UnknownHostKey, while using JSch SFTP library?
Or you do not know the host public key, and then you cannot create a secure connection (and the StrictHostKeyChecking=no is your only option).
See my article about verifying the host key to understand, what is it about, and its importance. The article is about WinSCP client, but it's valid in general for any SSH client.