Search code examples
javasshexecute

How to execute ssh bash command from java code?


I know there is a lot of thread about this problem but I dont found right: I follow this example: Want to invoke a linux shell command from Java to run command. Problem with ssh command is in authentication. When I run it I need to set password

$ ssh root@server 'fgrep Exception *.log*' 
Enter passphrase for key '/././.ssh/id_rsa':

How can I pass here password ?


Solution

  • There are libraries are available to invoke ssh. The Java Secure Channel (JSCH) is a very popular library, used by maven, ant and eclipse. It is open source with a BSD style license.

    If you need authentication for ssh, you can use through java.

    If your still need to by pass password passing, there are two ways to do what you want. One involves a stored password, and one does not.

    Both are non-interactive, meaning that they can work when you're not there to enter a password.

    1. The way that does not require a password. You can use public/private key authentication instead of passwords with SSH. I'm going to assume that you're using OpenSSH, which comes with practically every Linux distribution.

      Steps :

      • Configure your SSH server to accept private key logins. In /etc/ssh/sshd_config make sure that there's a line that says PubkeyAuthentication yes (and that there is no # infront of it). If you change this file, you need to restart the sshd service.

      • On your local machine (not the server), create yourself a pair of keys with ssh-keygen -t rsa (you can use other options than rsa, but I'm keeping it simple). Do not specify a password. Save the keys in the locations prompted.

      • Open the contents of the id_rsa.pub file that you just created (it's one very long line of text), and copy the contents into the end of the file $HOME/.ssh/authorized_keys on the server machine. Create the file if it doesn't exist.

      Further Detail refer here.

    2. The basic idea is to use expect, which is an administration automation tool, to type your password in to ssh when prompted. It might not always work, and when it doesn't, it's hard to figure out why not. I recommend the first method.

      Anyway, here's a command that you can poke at until it does what you want.

    The script Code is:

        expect -c 'spawn ssh [email protected] ; expect assword ; send  "passphrase\n" ; interact'
    

    Expect might not be installed on your system. Make sure install that