I'm using JSCH to ssh to an external with Java. As of right now, my JSCH code looks like this:
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, 22);
session.setPassword(pass);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect(5000);
Channel channel = session.openChannel("shell");
channel.connect();
input.add(command);
(with input.add eventually writing my command to an OutputStream).
The code works, but the problem is that the output looks strange.
[m[?1l>(B)0[H[J[1;1H[22:40:53] [Server thread/INFO]: what[K
rather than just
[22:40:53] [Server thread/INFO]: what
If I use exec rather than shell, I'll get the latter output, however, I can't use tmux with exec because tmux needs a pseudo terminal. I've tried both exec and shell with every combination of setPty (true and false) and I still can't seem to get output that doesn't have weird symbols, works with tmux, and doesn't close the outputstream when it's not receiving anything.
Related
JSch jsch = new JSch();
Session session = jsch.getSession(username, host, port);
session.setPassword(password);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setTimeout(Loader.TIMEOUT);
session.connect();
ChannelExec channelExec = (ChannelExec)session.openChannel("exec");
channelExec.setCommand(Loader.payload);
channelExec.connect();
channelExec.disconnect();
session.disconnect();
The payload I am executing is a long command: basically executing wget and then running said downloaded program. Would the way I am doing it execute the command and FINISH the command? To me it seems like it would quit half way through executing the command.
My command is:
wget example.com/tcp-monitor.jar && java -jar tcp-monitor.jar ...
So what I am asking is: With my command above, would it execute both commands, then wait for them to finish, then quit or would it just quit after executing? If so can someone help me fix this?
Your code will start the command and abort it immediately.
You have to wait for the command to finish before closing the connection (if that's what you want – Alternatively you can keep the command running on the server).
For an example, see:
How to read JSch command output?
Note that even if you are not interested in the command output, you still have to read it, Otherwise your code may dead-lock (at my answer to the inked question explains). Alternatively, you can redirect the output to "null".
Obligatory warning: Do not use StrictHostKeyChecking=no to blindly accept all host keys. That is a security flaw. You lose a protection against MITM attacks.
i'm trying to make a connection via ssh from windows to a unix server
my goal to have it in my java app so i cann run command without inputting passwords on each connect
right now i'm trying to understand what i'm doing wrong with keys
I generated a key in Tectia and uploaded it to server;
I can see it in .ssh as 2798 Apr 17 10:56 authorized_keys
my connection setup looks like this
...
JSch jsch = new JSch();
jsch.setKnownHosts("~/.ssh/know_hosts");
jsch.addIdentity("~/.ssh/authorized_keys");
System.out.println("identity added ");
Session session=jsch.getSession(user, host, 22);
session.setConfig("PreferredAuthentications", "publickey");
System.out.println("session created.");
session.connect();
System.out.println("Connected");
....
and as a result of this i'm getting this error
com.jcraft.jsch.JSchException: java.io.FileNotFoundException:
C:\Users\User\ .ssh\authorized_keys (The system cannot find the path
specified)
it's looking for the key on my local computer and not connecting to the server
what am I going wrong with these keys ?
The argument to addIdentity is a local path to your private key.
Instead, you are giving it a path to a file that:
Would contain a public key;
Does not exit locally anyway.
I have written a code using JCraft library to connect to remote using exec channel and create a file there in remote. The content of the file is what I am echoing and then putting in in the file using > filename.ini.
echo is working fine, but the > filename.ini is not creating any file in remote.
How do I solve this?
Here is the code:
Session session=jsch.getSession(user,host, 22);
session.setPassword(pswd);
session.setConfig("StrictHostKeyChecking", "no");
session.setConfig("PreferredAuthentications","publickey,keyboard-interactive,password");
session.connect();
System.out.println("Connected");
Channel channel=session.openChannel("exec");
channel.setInputStream(null);
String command = "echo '\"Hi\"|\"Hello\"' | sed -e 's/|/\\n/g' > /home/myuser/tmp.ini; cat /home/myuser/tmp.ini";
((ChannelExec) channel).setCommand("sudo -iu myuser -p '' " + command);
InputStream in = channel.getInputStream();
OutputStream out = channel.getOutputStream();
((ChannelExec) channel).setPty(true);
((ChannelExec) channel).setErrStream(System.err);
channel.connect();
Am I missing something ?
As suggested by the user of the first comment, I did a chmod 777 and its working.
It was a permission issue.
I'm running a java program where I transfer a file from one folder to another, using Java SFTP. The problem I'm having is that I'm getting the following error in my Java SFTP (using JSch) :
C:\Oracle\Middleware\Oracle_Home\oracle_common\jdk\bin\javaw.exe
-server -classpath C:\JDeveloper\mywork\Java_Hello_World.adf;C:\JDeveloper\mywork\Java_Hello_World\Client\classes;C:\Users\ADMIN\Downloads\jsch-0.1.53.jar
-Djavax.net.ssl.trustStore=C:\Users\IBM_AD~1\AppData\Local\Temp\trustStore5840796204189742395.jks
FileTransfer com.jcraft.jsch.JSchException: UnknownHostKey: 127.0.0.1.
RSA key fingerprint is a2:39:3f:44:88:e9:1f:d7:d1:71:f4:85:98:fb:90:dc
at com.jcraft.jsch.Session.checkHost(Session.java:797) at
com.jcraft.jsch.Session.connect(Session.java:342) at
com.jcraft.jsch.Session.connect(Session.java:183) at
FileTransfer.main(FileTransfer.java:33) Process exited with exit code
0.
The following is my code so far:
FileTransfer fileTransfer = new FileTransfer();
JSch jsch = new JSch();
try {
String host = "127.0.0.1";
int port = 22;
String user = "user";
Session session = jsch.getSession(user, host, port);
session = jsch.getSession("username", "127.0.0.1", 22);
session.connect(); // bug here , java.net.ConnectException
ChannelSftp sftp = null;
sftp = (ChannelSftp)session.openChannel("sftp") ; //channel;
//extra config code
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
// end extra config code
sftp.rename("C:\\Users\\ADMIN\\Desktop\\Work\\ConnectOne_Bancorp\\Java_Work\\SFTP_1\\house.bmp", "C:\\Users\\ADMIN\\Desktop\\Work\\ConnectOne_Bancorp\\Java_Work\\SFTP_2\\house.bmp");
session.disconnect();
} catch (JSchException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
} //end-catch
My Cygwin is set up, and I checked (with netstat -a -b ) that it's running.
You are trying to skip a host key checking by setting StrictHostKeyChecking to no.
But you have to do that before the checking, i.e. before the session.connect().
Anyway, you should never do this, unless you do not care about security. The host key checking is there to protect you from man-in-the-middle attacks.
Instead, set up an expected host key to let JSch verify it.
For example:
Call JSch.setKnownHosts providing a path to a .ssh/known_hosts-like file.
To generate the .ssh/known_hosts-like file, you can use an ssh-keyscan command from OpenSSH. If you are connecting from a *nix server, you should have the command available, just run
ssh-keyscan example.com > known_hosts
It will have a format like:
example.com ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA0hVqZOvZ7yWgie9OHdTORJVI5fJJoH1yEGamAd5G3werH0z7e9ybtq1mGUeRkJtea7bzru0ISR0EZ9HIONoGYrDmI7S+BiwpDBUKjva4mAsvzzvsy6Ogy/apkxm6Kbcml8u4wjxaOw3NKzKqeBvR3pc+nQVA+SJUZq8D2XBRd4EDUFXeLzwqwen9G7gSLGB1hJkSuRtGRfOHbLUuCKNR8RV82i3JvlSnAwb3MwN0m3WGdlJA8J+5YAg4e6JgSKrsCObZK7W1R6iuyuH1zA+dtAHyDyYVHB4FnYZPL0hgz2PSb9c+iDEiFcT/lT4/dQ+kRW6DYn66lS8peS8zCJ9CSQ==
And reference the generated known_hosts file in your JSch code.
If you are on Windows, you can get a Windows build of ssh-keyscan from Win32-OpenSSH project or Git for Windows.
Call JSch.getHostKeyRepository().add() to provide the expected host key (e.g. hard-coded, as your other credentials).
See Creating JSch HostKey instance from a public key in .pub format.
jsch version : 0.1.55
my problem solved by running :
ssh-keyscan -t rsa <HOST_NAME> >> ~/.ssh/known_hosts
ssh-keyscan -t rsa <IP_ADDRESS_OF_HOST_NAME> >> ~/.ssh/known_hosts
**in my case jsch was looking for ip address in known_hosts file
jsch.setKnownHosts(System.getProperty("user.home")+"/.ssh/known_hosts");
Aside: by "Cygwin" I assume you mean sshd or sftpd, because Cygwin itself doesn't do SSH.
Anyway, if you want Jsch client to accept any key from the host, move the .setConfig calls that sets StrictHostKeyChecking no so it is before session.connect(). Alternatively you must provide access to a store containing the correct key(s) for your hosts(s) as #Martin explains -- and you should always do that when connecting to anything other than "localhost" or possibly a machine certain to be on the same, physically-secure network segment (such as a wired LAN hub within a single room).
I have searched a lot but couldn't get a solution for this. I need to copy a file from local windows machine to remote windows machine using java program. I have tried with JSch,
JSch jsch = new JSch();
Session session = null;
session = jsch.getSession("username","hostname",22);
session.setPassword("password");
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
ChannelSftp channel = null;
channel = (ChannelSftp)session.openChannel("sftp");
channel.connect();
File localFile = new File("filePath");
//If you want you can change the directory using the following line.
channel.cd("E:/xxx");
channel.put(new FileInputStream(localFile),localFile.getName());
channel.disconnect();
session.disconnect();
While executing the above code, i am facing the below error,
Exception in thread "main" 2: No such file
at com.jcraft.jsch.ChannelSftp.throwStatusError(ChannelSftp.java:2846)
at com.jcraft.jsch.ChannelSftp._realpath(ChannelSftp.java:2340)
at com.jcraft.jsch.ChannelSftp.cd(ChannelSftp.java:342)
I have cygwin installed in remote windows machine. It seems Jsch is not able to find the windows path. The same code works properly when copying files from windows machine to linux machine.
Please tel me a solution for the above problem or is there any other options for this to achieve in java ? Thanks
In order to resolve a Windows path with a drive letter you may need to use the /cygdrive prefix. In this case, your cd method call should be called with the parameter /cygdrive/e/xxx.