Change file permissions with SFTP or SCP uing JSch - java

I have a user account, but on trying using this am getting exception for rssh. Is there any possibility to give permission of directory using other way other than ChannelExec. Based on the exception I come to know this account can't use ChannelExec to give permission of a directory or file. Thus is there any other way this account could give file permission without getting access to this user account for rssh. Please give you thoughts.
Code :
channelSftp = (ChannelSftp) channel;
ChannelExec channelexe = (ChannelExec) session.openChannel("exec");
channelexe.setCommand("chmod 777 -R " + depDir);
channelexe.connect();
System.out.println("channelexe.getExitStatus:"+channelexe.getExitStatus());
Output :
channelexe.getExitStatus:-1:
This account is restricted by rssh.
Allowed commands: scp sftp
If you believe this is in error, please contact your system administrator.

There's no need to use the "exec" channel for this.
Use the ChannelSftp.chmod:
public void chmod(int permissions, String path)
Note that the method takes the permissions as an integer. So you cannot use 777, as that's an octal representation of the permissions.
An equivalent decimal representation is 511 (= 7*8^2 + 7*8^1 + 7*8^0).
See also Decimal to Octal Conversion.
Though the ChannelSftp.chmod cannot set permissions recursively. The SFTP protocol does not support recursive operations of any kind.

Related

How to check whether user exists in Linux (JSch)

I am connecting/creating users in Linux machine using JSch. I am successfully able to connect Linux machine and create users. But i'm not able to check whether that user already exists or not in machine, while creating user. For this i tried command: id -u name
And my implementation is:
System.out.println("Connected");
Channel channel=session.openChannel("exec");
((ChannelExec)channel).setCommand("id -u name");
channel.setInputStream(null);
((ChannelExec)channel).setErrStream(System.err);
InputStream in=channel.getInputStream();
channel.connect();
But it doesn't tell whether its true or false. How to do this using JSch to check whether user exists in Linux?.
You are reading the InputStream that will have the user's id if you are asking for an existing user, but if you are asking for a user that is not in the system, the output will be written in the error stream. If you want to read one stream, you could modify your command to print the exit status of the last command executed.
session.connect();
ChannelExec channel = (ChannelExec) session.openChannel("exec");
channel.setCommand("id -u name; echo $?");
channel.connect();
The output if you ask for an exist user will have 2 lines, the first one will be the user's id, and the second one will be 0 that means executed successfully, if the user doesn't exists the content of the stream will be different of 0 that means command failed to execute.

channelExec.setCommand() Not Working when executing shell commands

I'm executing .sh file in a remote server and it is not working properly. For that i used JSch and java. and this is how i tried.
ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
InputStream in = channelExec.getInputStream();
channelExec.setCommand("cd /home");
Here is a full example http://myitlearnings.com/java-code-to-run-a-remote-script-on-remote-host-using-ssh/ .
Add this below statement, so the security measure is by passed // By default StrictHostKeyChecking is set to yes as a security measure.
session.setConfig("StrictHostKeyChecking", "no");
Add full code base (ip not required while sharing the code) and error message received. Add Proper exception handling, so we will get to know what is the error you are getting and can assist better

Setting ASCII mode in Jsch

I need to overcome a Unix - Windows file format (LF to CRLF) issue I'm currently having.
The ftp client I am using is Jsch from Jcraft.
The documentation online is very bare, although I have come across a flag that can be set
SSH_FXF_TEXT_MODE
that enables ASCII mode, but I don't see where I should set this in the code itself, nor do I see it mentioned in these Javadocs
Below is my own attempt at a workaround.
The "Newly Added" line shows how I take the file and convert it to an ASCII encoded string, which I then transfer across using the channelSftp put method.
Originally I would have just put the file itself across.
final JSch jsch = new JSch();
final Session session = jsch.getSession(username, host);
session.setPassword(password);
session.connect();
final Channel channel = session.openChannel("sftp");
channel.connect();
final ChannelSftp channelSftp = (ChannelSftp) channel;
channelSftp.cd(destDir);
File file = new File(pathName);
String content = FileUtils.readFileToString(file, "US-ASCII"); // Newly Added
channelSftp.put(content, fileToTransfer.getName());
Please note that I omitted exception handling and other practices just for clarity of the code snippet.
Will this workaround succeed, or will Jsch's seemingly default binary mode override the ASCII encoded string and transfer it as usual?
I will test it, I was just wondering if any of you could tell straight off?
Or indeed knew how/where to set the Text_Mode flag! :)
Also, the version of Jsch I am using is jsch-0.1.49.jar.
The text mode flag was added to SFTP protocol version 4. Jsch currently supports SFTP protocol version 3, which doesn't specify a text-mode flag.
You can see a list of SFTP specification revisions here. The RFC for protocol version 3 is here. Note that OpenSSH, the most widely used SFTP server, only supports protocol version 3 as well, and doesn't support line terminator conversion. So having the flag in Jsch wouldn't be very useful.

using jsch( JCraft) i need to pg a unix text file

i need to connect to ssh server and pull out data of a huge file.
iam able to do it with cat command , and it takes nearly 10 -15 mins time.
The challange here is, i cant user sftp , exe
i.e Channel channel = session.openChannel("sftp"); & Channel channel = session.openChannel("exec"); not allowed in my prd environment.
The only option left behind is "shell".
Can anyone tell me how to do pg , until a specific pattern is found in the file.
Please help me with a code example !!
Hope you got my query . Thanks in advance.
How about following sample program?
https://gist.github.com/4482587
It will remotely exec "gzip -c", and gunzip the given data stream.

How to SSH to a server behind another SSH server using JSch?

I need to be able to ssh from a Java program into a remote server, and from there SSH to another server. I have credentials for both servers on my client.
The commands will be passed automatically from within the app as regular strings (no user input). I need to be able to run those custom commands on the second server and be able to decide what commands to issue during runtime, based on the output and some simple logic.
Can I use JSch to do that and if yes, where should I start look into? (Examples, info)
=============================================================
ADDED:
Exception in thread "main" com.jcraft.jsch.JSchException:
UnknownHostKey: host.net. RSA key fingerprint is 'blahblahblah'
as till now, I am solving this problem by modifying the known_hosts file and adding host manually in there.
Can I bypass this little problem by settings an option somewhere telling the JSch to press YES automatically when this YES-NO question is asked?
To connect to a second server behind a firewall, there are in principle two options.
The naive one would be to call ssh on the first server (from an exec channel), indicating the right server. This would need agent forwarding with JSch, and also doesn't provide the JSch API to access the second server, only the ssh command line.
The better one would be to use the connection to the first server to build up a TCP Tunnel, and use this tunnel to connect to the second server. The JSch Wiki contains a ProxySSH class (together with some example code) which allows to use a JSch session as a tunnel for a second JSch session. (Disclaimer: This class was written mainly by me, with some support from the JSch author.)
When you have your connection to the second server, use either a shell channel or a series of exec channels to execute your commands. (See Shell, Exec or Subsystem Channel in the JSch Wiki for an overview, and the Javadocs for details.)
For your unknown-host-key problem:
The secure version would be to collect all host keys (in a secure way) before and put them in the known_hosts file. (If you simply trust the key which is presented to you, you are vulnerable to a man-in-the-middle attack. If these are of no concern in your network, since it is physically secured, good for you.)
The convenient version is setting the configuration option StrictHostKeyChecking to no - this will add unknown host keys to the host keys file:
JSch.setConfig("StrictHostKeyChecking", "no");
(You can also set it individually on the sessions, if you only want to set it for the proxied sessions and not for the tunnel session. Or override it for the tunnel session with yesor ask - there the MITM danger might be greater.)
A middle way would be to enable actually asking the user (which then should compare the fingerprints to some list) - for this, implement the UserInfo interface and provide the object to the session. (The JSch Wiki contains an example implementation using Swing JOptionPanes, which you can simply use if your client program runs on a system with GUI.)
For the saving of accepted host keys to work, you must use the JSch.setKnownHosts method with a file name argument, not the one with an InputStream argument - else your accepting will have to be repeated for each restart of your client.
Use an SSH tunnel, aka local port forwarding, to open an SSH/SFTP connection to B via A.
Session sessionA = jsch.getSession("usernameA", "hostA");
// ...
sessionA.connect();
int forwardedPort = sessionA.setPortForwardingL(0, "hostB", 22);
Session sessionB = jsch.getSession("usernameB", "localhost", forwardedPort);
// ...
sessionB.connect();
// Use sessionB here for shell/exec/sftp
You may need to deal with UnknownHostKey exception.
This can help anyone. Works fine:
public static void sesionA(){
try {
Session sessionA = jSch.getSession(username, hostA);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
sessionA.setConfig(config);
sessionA.setPassword(passwordA);
sessionA.connect();
if(sessionA.isConnected()) {
System.out.println("Connected host A!");
forwardedPort = 2222;
sessionA.setPortForwardingL(forwardedPort, hostB, 22);
}
} catch (JSchException e) {
e.printStackTrace();
}
}
public static void sesionB(){
try {
Session sessionB = jSch.getSession(username, "localhost", forwardedPort);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
sessionB.setConfig(config);
sessionB.setPassword(passwordB);
sessionB.connect();
if(sessionB.isConnected()) {
System.out.println("Connected host B!");
}
}
}

Categories