I am getting an exception while using SSHJ.
Here is how I implemented it:
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
final SSHClient ssh = new SSHClient();
ssh.loadKnownHosts();
ssh.connect("serverName");
try{
ssh.authPublickey("myUserId");
final Session session = ssh.startSession();
try{
final Command cmd = session.exec("net send myMachineName Hello!!!");
System.out.println(cmd.getOutputAsString());
System.out.println("\n Exit Status: "+cmd.getExitStatus());
}finally{
session.close();
}
}finally{
ssh.disconnect();
}
}
}
But I get the following exception:
Exception in thread "main" java.io.IOException: Could not load known_hosts
at net.schmizz.sshj.SSHClient.loadKnownHosts(SSHClient.java:528)
at SSHTEST.main(SSHTEST.java:25)
What am I doing wrong?
Use the folowing code
final SSHClient ssh = new SSHClient();
ssh.addHostKeyVerifier(
new HostKeyVerifier() {
public boolean verify(String arg0, int arg1, PublicKey arg2) {
return true; // don't bother verifying
}
}
);
ssh.connect("LocalHost");
Remove the call to loadKnownHosts() method, which as erickson mentioned checks under ~/.ssh/known_hosts by default (you can specify the location as an argument as well though), and replace it with:
ssh.addHostKeyVerifier("public-key-fingerprint");
To find out what the fingerprint is, the twisted way would be to connect without that statement - you'll find out from the exception ;-)
It sounds like it's trying to read a "known_hosts" file, but can't find it, or possibly it in an invalid format.
The SSH known hosts file records the public key for various hosts to thwart some spoofing attacks. Normally it resides in ~/.ssh/known_hosts. Try creating an empty file there and see if that satisfies the library.
The library documentation is likely to address the necessary configuration files.
Related
So what I'm trying to do, is create unit test that checks if invoked command (on shell via ssh connection) has a proper response. The problem is that I can't read those responses. There are not many tutorials regarding Apache MINA, so I thought maybe some of you could help me out. Here's a code
#Before
public void setUpSSHd() {
sshd=SshServer.setUpDefaultServer();
sshd.setPort(22999);
sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider("hostkey.ser"));
sshd.setPasswordAuthenticator(new PasswordAuthenticator() {
public boolean authenticate(String username, String password, ServerSession session) {
// TODO Auto-generated method stub
return true;
}
});
List<NamedFactory<KeyExchange>> keyExchangeFactories;
keyExchangeFactories = sshd.getKeyExchangeFactories();
sshd.setKeyExchangeFactories(keyExchangeFactories);
try {
sshd.start();
} catch (Exception e) {
e.printStackTrace();
}
}
#After
public void teardown() throws Exception { sshd.stop(); }
#Test
public void testCommands() throws Exception {
SshClient client = SshClient.setUpDefaultClient();
client.start();
ClientSession session = null;
try {
session = client.connect("localhost", 22999).await().getSession();
session.authPassword("none", "none").await().isSuccess();
System.out.println("Connection established");
final ClientChannel channel = session.createChannel(ClientChannel.CHANNEL_SHELL);
ByteArrayOutputStream sent = new ByteArrayOutputStream();
PipedOutputStream pipedIn = new TeePipedOutputStream(sent);
channel.setIn(new PipedInputStream(pipedIn));
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayOutputStream err = new ByteArrayOutputStream();
channel.setOut(out);
channel.setErr(err);
channel.open();
pipedIn.write("dir\r\n".getBytes());
pipedIn.flush();
channel.waitFor(ClientChannel.CLOSED, 0);
channel.close(false);
client.stop();
System.out.println(out.toString());
} catch (Exception e) {
e.printStackTrace();
fail("Cannot establish a connection");
} finally {
if (session != null)
session.close(true);
}
}
For now I simply try to print out collected response. However I get empty string everytime I try to do that. I assume there might be a problem with ssh server configuration (what shell is it supposed to use?). The best scenario would be if I could define my own commands and responses on server side and then, only check it on client side
EDIT: I've tried to manually connect to this mocked ssh server but I've got
Unable to negotiate with ::1 port 22999: no matching key exchange method found. Their offer: diffie-hellman-group1-sha1
error message.
I would suggest you to update Apache SSH. Based the source repository the version 0.5.0 is 7 years old.
using your posted code with the default JCE provider and Apache SSH
<dependency>
<groupId>org.apache.sshd</groupId>
<artifactId>sshd-core</artifactId>
<version>0.5.0</version>
<dependency>
the connect with a ssh client fails with
Their offer: diffie-hellman-group1-sha1
using a more recent Apache SSH release
<dependency>
<groupId>org.apache.sshd</groupId>
<artifactId>sshd-core</artifactId>
<version>1.4.0</version>
<dependency>
the connect is successful
Hi Below is a sample code I've written:
import com.siebel.data.*;
import com.siebel.data.SiebelException;
public class DataBeanDemo
{
private SiebelDataBean m_dataBean = null;
private SiebelBusObject m_busObject = null;
private SiebelBusComp m_busComp = null;
public static void main(String[] args)
{
DataBeanDemo demo = new DataBeanDemo();
}
public DataBeanDemo()
{
try
{
m_dataBean = new SiebelDataBean();
m_dataBean.login("Siebel://devServerXYZ:7777/XYZ/
ecommunication_enu", ROSADMIN, ROSADMIN, "enu");
System.out.println("Connected");
m_busObject = m_dataBean.getBusObject("Opportunity");
m_busComp = m_busObject.getBusComp("Opportunity");
m_dataBean.logoff();
}
catch (SiebelException e)
{
System.out.println(e.getErrorMessage());
}
}
}
This code executes without issues, but gets stuck at m_dataBean.login(). And never returns.
What could be the issue?
If I try to change connect string (even port name, from 7777 to any other number like 2320, 2321) then I get error could not open a session in 4 attempts SBL-JCA-00200.
3 things to verify
Parameters in the connect string. Gtway server name, OM comp name, port number etc. (Username/Password error is showed immediately but rest others throw generic errors or hung forever)
(This is something that's specific to Siebel) Ensure that Java subsystem profile has classpath pointing to siebel.jar and siebelJI_lang.jar files
Siebel Server is up and running.
If LDAP is true, then such logins cannot be used using Databeans.
In my case it was 1 & 2, that was causing issues. By the way Comp name is case sensitive.
magento api using soap doesn't work due to missing magento-api.properties files, can someone help?
public class testConnection {
public static void main(String[] args) throws AxisFault {
String user = "rajeshvishnani";
String pass = "123456";
String host = "http://cypherincorporated.co.in/magento/index.php/api/soap?wsdl";
SoapConfig soapConfig = new SoapConfig(user, pass, host);
MagentoSoapClient magentoSoapClient = MagentoSoapClient.getInstance(soapConfig);
magentoSoapClient.setConfig(soapConfig);
}
}
Exception in thread "main" java.lang.IllegalArgumentException: could not load [magento-api.properties] as a classloader resource
at com.google.code.magja.utils.PropertyLoader.loadProperties(PropertyLoader.java:106)
at com.google.code.magja.utils.PropertyLoader.loadProperties(PropertyLoader.java:123)
at com.google.code.magja.soap.MagentoSoapClient.getInstance(MagentoSoapClient.java:69)
at magentomanager.testConnection.main(testConnection.java:15)
Try changing the url to 'http://yoursite.com/api/v2_soap/index?wsdl=1'.
Please provide more details.
Not sure about java exception but you can try following link.
Link
I am trying to implement a feature to restart PostrgeSQL server from Java code using Runtime.getRuntime().exec() method. The method is working fine if the PostgreSQL server is not SSL enabled but if the PostreSQL server is SSL enabled and if the private key is encrypted with a password, it requires passphase to be passed. I tried with below code for implementing the same,
String postgreSQLRestartCMD =
"/u/postgreSQL/pg_ctl -D /u/postgreSQL/data restart -w";
//-w option waits until the passphase is sent
final Process restartPosgreSQLServer = Runtime.getRuntime().exec(postgreSQLRestartCMD);
PrintStream ps = new PrintStream(restartPosgreSQLServer.getOutputStream());
ps.println("keyPassword"); // sending passphasse here
new Thread(new Runnable() {
#Override
public void run() {
try {
IOUtils.copy(restartPosgreSQLServer.getInputStream(), logWriter);
}
catch (final IOException e) {
logWriter.println("Error occurred while reading InputStream.");
e.printStackTrace(logWriter);
}
}
}).start();
new Thread(new Runnable() {
#Override
public void run() {
try {
IOUtils.copy(restartPosgreSQLServer.getErrorStream(), logWriter);
}
catch (final IOException e) {
logWriter.println("Error occurred while reading ErrorStream.");
e.printStackTrace(logWriter);
}
}
}).start();
int returnStatus = restartPosgreSQLServer.waitFor();
if (returnStatus == 1) {
logWriter.println("Error has occured while running PostgreSQL server.");
} else {
logWriter.println("PostgreSQL has started successfully.");
}
But the server is not getting started. I am trying in Linux. In console its getting struck with below line and I guess passohase not sent properly.
Enter PEM pass phrase:
Where is this going wrong and why is the passphase not sent?
Edit
Upon digging further I just found that Runtime.getRuntime().exec(cmd) is creating new process, my ps.println("password") is passed to parent process. But I am not sure, whether my observation is right.
What you are not taking into account is that before programs ask for the password, they flush the input buffer. Otherwise it would be very easy to have extra characters read in for password, that the user accidentally typed before the password prompt.
You'll have to raise the level of complexity of your code to analyze the process's output and print to its stdin only after actually witnessing the password prompt.
I am trying to get a rmi connection going. I have ran into many security issues but have been unable to find a way past all this. I execute my jar file with:
java -Djava.security.policy=java.security.AllPermission -jar "myjarfile"
The code I have been using to create this is:
public class server
{
public static void main(String args[])throws Exception
{
if (System.getSecurityManager() == null)
System.setSecurityManager ( new RMISecurityManager() {
public void checkConnect (String host, int port) {}
public void checkConnect (String host, int port, Object context) {}
});
try
{
sampleserverimpl server = new sampleserverimpl();
System.out.println("SERVER IS WAITING");
LocateRegistry.createRegistry(2020);
//Runtime.getRuntime().exec("rmiregistry 2020");
Naming.rebind("//localhost:2020/SERVER", server);
}
catch(Exception e)
{
System.out.println(e);
}
}
};
The error trace I am receiving is:
Exception in thread "RMI TCP Connection(idle)" java.security.AccessControlExcept
ion: access denied (java.net.SocketPermission 127.0.0.1:31199 accept,resolve)jav
a.rmi.UnmarshalException: Error unmarshaling return header; nested exception is:
java.io.EOFException
I have tried different ways to get around this, can anyone see the issue here?
Thanks
-Djava.security.policy accepts a URL which points to a policy file which in turn contains the permissions. So you should have: -Djava.security.policy=/some/path/my.policy as the JVM argument where the my.policy file contains:
grant {
permission java.security.AllPermission;
};
Also, in order to avoid the NULL check present in your code and the manual creation of a SecurityManager, you can request a SecurityManager be automatically installed for your application by passing the JVM switch: -Djava.security.manager.
Your final JVM invocation should look like:
java -Djava.security.manager -Djava.security.policy=/some/path/my.policy
This is two separate exceptions. The first is a permission problem. The second one, the EOFException, could have any of a number of causes. I would need to see java -version and the complete stack trace to assist further.