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 ?
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.
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.
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 user#remote.host ; expect assword ; send "passphrase\n" ; interact'
Expect might not be installed on your system. Make sure install that
You need to get the InputStream (which has the output) from the execution and wait for it to ask you for the password, then get the OutputStream (into which you give the command its input) and send it the password you want.
Have a read of this article
Related
I have been facing a strange issue in running scp command via my java application.
I am supposed to run this scp command with "-i" option where in ,I pass the identify key of a low privileged user(for an instance user B) while my java process is run by another logged in user(for an instance user A).
This is how my command looks in the application log when it's run by the logged in user "user A".
scp -l 10000 -o BatchMode=yes -o LogLevel=DEBUG -i "PathToIdentitykeyOfuserB" remoteUser#remoteHost:"PathToRemoteFile" "localPathofCopiedFile"
This command fails in my java application with errors saying
stdErr: Warning: Identity file not accessible: No such file or directory.
stdErr: remoteUser#remoteHost: Permission denied (publickey,password,keyboard-interactive).
what makes me wondering is the very same command runs perfectly, when it is run either in cygwin command line or windows command line.
I later added "-o LogLevel=DEBUG" in order to debug the internal logging for scp command to ascertain any difference in the logging informations of scp command itself (when it was run in windows cmd line) and when it is run via process builder of java application.
I observed that while SCP's(run through user A in windows command line)internal logging says it takes in the very same identity key of user B but its not this case when scp is run via process builder in my java application. Internal debug logging of SCP shows that it attempts to authenticate using the default private key of user A even after explicitly passing the identity key of user B.
Please find below few screenshots.
Identity key loaded in the SCP's internal logging from Windows CMD.
Authentication successful via Window CMD
Identity Key loaded in SCP's internal logging from process builder of java Application.
I fail to understand as to why SCP does not attempt to authenticate with the explicitly passed identity key of user B but rather tries to authenticate with its default identity key(user A).
However, its evident from the attached screenshots that from windows command line, it authenticates with the explicitly passed identity key and as a result, authentication succeeds.
I request experts to help me out with some tips to resolve this problem.
How can I make the process builder to take into account the identity key of passed identity key of another user instead of default key of user initiating it?
Any help would be greatly appreciated.
Here is how, I was creating process builder.
I have created a list of strings which basically holds scp command constructed with the list of strings and then pass this list directly as a parameter to command method of process builder.
I have managed to solve it now by creating a temporary file and then writing scp commands to it and run this temporary file in the process builder as against running scp command directly in the process builder earlier.
Instead of passing the list of strings which was used to construct scp command and passing the same to process builder, I have resorted to creating a temporary file and then writing scp command to it and lastly running this temporary file by passing to java process builder.
This solution seems to work now for me.
i try to connect to sftp server in my local machine i generate the knownHosts file with the command ssh
and i use it like jsch.setKnownHosts(knownHosts);
but i would to run my job in other machine wish i didn't have access to his knownHosts file
so i decided to disable the check of this rsa key and i wont to know if the action is safe
i will use this line to disable it
session.setConfig("StrictHostKeyChecking", "no");
The question itself has a comment about its safety, but I would like to add that if you don't want to have the StrictHostKeyChecking set as "no", and do not want to rely on a knownHosts file, I would recommend you to:
1) Generate the host fingerprint in a way that's compatible with Jsch, please refer to this question. You can output the generated fingerprint to another file or elsewhere as needed.
2) You can then get the generated value and store it as a variable (environment variable, config file, property, etc.) so that your application can use it. You can pass this fingerprint (not filepath) to Jsch with the setKnownHosts method.
I have a server where I work with a database and files using a java app.
When I start my app I give a report regarding file access to the server using:
public static boolean folderExists(String folderPath) {
File folderToCheck = new File(folderPath);
return folderToCheck.exists();
}
Every time I start my app (after a fresh restart of my computer)
I get a false response, even though the server is on.
The reason is because I must give an authentication as another user.
What I do is access the server through Windows
where I am being asked for username/password,
and after that I get a true response regarding file access to the server.
Is there a way to give the authentication username/password through Java,
and not through Windows?
Thank you
On Windows 'native' Java IO (e.g. java.io.File) always inherits the security context of the user running the JVM process. For example, you could run the Java app as a Windows service with the correct credentials.
The JCIFS project implements CIFS (the Windows SMB file server protocol) and allows you to directly specify the username/password.
See the API for examples.
I am pretty sure, that there is no way to grant fileaccess by java, without a Windows-Call.
You can call cacls file.log /e /t /p Everyone:f but this will be language-dependent.
I had a similar problem: How to change the file ACL in windows, if I only know the SID?
With Java7 there may be a way to do this.
I'm trying to make a Java application, that executes shell scripts on a remote Unix server, using the JSch API.
I was wondering if it's possible to login to the server without a password. If so - how? Should I generate a pair of authentication keys on the servers, then make the application read information from the key file?
The Java application is on a Windows station.
Since it took awhile before made it work, here is a whole modified example:
JSch jsch=new JSch();
Session session=jsch.getSession("my_username", "my_host", my_port);
session.setConfig("PreferredAuthentications", "publickey");
jsch.setKnownHosts("~/.ssh/known_hosts");
jsch.addIdentity("~/.ssh/id_rsa");
session.setConfig("StrictHostKeyChecking", "no");
session.connect(30000);
Channel channel=session.openChannel("shell");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect(3*1000);
Beware whether you have copied rsa or dsa key to the server and add a corresponding identity at line addIdentity - id_rsa or id_dsa.
(cat .ssh/id_rsa.pub | ssh me#servername 'cat >> .ssh/).
This is certainly doable. Have a look at the examples directory provided with jsch.
UserAuthPubKey.java is showing how to authenticate with a public key and and KeyGen.java is chowing how to create the public and private keys.
Once you have sorted out your keys there is a single line to enable connecting with a key rather than a password:
JSch jsch = new JSch();
jsch.addIdentity(".ssh/privateKey.pem");
The addIdentity method takes a single argument that points at the location of your private key file on your machine.
As said by jlliagre, it is possible.
Generate a key pair for your application, make the public key known to the server (often putting it in ~/.ssh/authorized_keys is a good way), and give both keys to the client JSch object, either as files or as byte[]. You might also want to change the PreferredAuthentications option to allow only public-key auth, to avoid asking for a password or trying something else.
Note: If you deliver your application to hosts not controlled by you, anyone which can access the application's files can use the private key to login to your server.
Thus you should make sure the account can't do anything harmful, or that the client machine (your account and any privileged one) is under your (or only known friendlies') total control. (Encrypting the private key with a passphrase does not help if the passphrase is distributed with your program. Neither does putting it in the program's jar file.)
As I'm uncomfortable storing my username and password (must auth to the proxy server with my normal login credentials) in plaintext in .m2/settings.xml, I'm trying to see if there is a better way to pass my credentials.
What I've tried
Relying on system proxy settings - didn't work (obviously)
Leaving out password - downloaded 5k - 740b jars. Right...
Adding -Dmaven.proxy.password=mypass to command line - Same as above
is there anyway I can pass this information over command line? Or even better, is there a way to have it prompt me for the password?
FYI, it works as expected when I do have the password in the configuration file
I have never used this particular feature of Maven, but they do have some support for encrypting passwords in your settings.xml. You can read more here: http://maven.apache.org/guides/mini/guide-encryption.html
That doesn't exactly answer your question, but it might solve your root problem.