Reputation: 31
Below is the code snippet
JSch jsch = new JSch();
session = jsch.getSession(SFTPUSER,SFTPHOST,SFTPPORT);
session.setPassword(SFTPPASS);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
config.put("PreferredAuthentications","publickey,keyboard-interactive,password");
session.setConfig(config);
session.connect();
After connecting to a session I need to switch to root in order to copy a file(as permissions are not enabled and also there is no option to root login directly).
channel = session.openChannel("exec");
((ChannelExec) channel).setCommand("dzdo -iu root");
and now I can copy files
channel = session.openChannel("sftp");
channel.connect();
channelSftp = (ChannelSftp)channel;
channelSftp.cd(SFTPWORKINGDIR);
System.out.println("connected successfully");
channelSftp.put(FILETOTRANSFER, SFTPWORKINGDIR);
Here am using both "exec" and "sftp" channels, but it is not working for me. Any help how to run a command and then copy files using "sftp"?
Upvotes: 3
Views: 2958
Reputation: 202642
Your code is correct. But if you expected the "exec" channel user switching operation to affect the "sftp" channel, you were wrong. The channels run in isolated environments.
The only way to do, what you want, is to explicitly run SFTP server in elevated environment. There's no generic solution for that and with some servers it may not even be possible.
Some references:
sudo
with WinSCP SFTP clientGenerally a need to switch the user to automate some operation, is a sign of a bad design. You should directly use an account that has an access to the resources you need for the task. The correct solution is to setup a dedicated private key with only privileges needed for your task.
Upvotes: 1