Connect with jsch to a switch using ssh - jsch

this is my first time I ask a question here so i dont know how to properly post one, but i will do my best. I have the Jsch library in java but I dont know to connect to the switch using ssh2. How do you but the hostkey of the switch in the session?
my code has something like this...
private static final String user = "admin";
private static final String host = "172.16.13.3";
private static final Integer port = 22;
private static final String pass = "";
public static void main(String[] args) throws Exception{
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setPassword(pass);
session.connect();
but when its executed the program runs without any errors, but it never connects to the switch.... Thanks for your help!!

Related

Error while running documentum code

I am getting an error while running the documentum code at:
config.setString("primary_host", docbroker);
in the below code:
IDfClient client = DfClient.getLocalClient();
// getting the config object of local client
IDfTypedObject config = client.getClientConfig();
config.setString("primary_host", docbroker);
IDfLoginInfo li = new DfLoginInfo();
and the error I was getting is below:
Error:
java.lang.IllegalStateException: Reference count is already zero
at com.documentum.fc.impl.util.ReferenceCountManager.decrement(ReferenceCountManager.java:47)
at com.documentum.fc.client.impl.docbroker.DocbrokerMapUnion.decrementReferenceCount(DocbrokerMapUnion.java:43)
at com.documentum.fc.client.impl.docbroker.DocbrokerMapUnion.removeEntry(DocbrokerMapUnion.java:37)
at com.documentum.fc.client.impl.docbroker.DocbrokerMap.removeEntries(DocbrokerMap.java:176)
at com.documentum.fc.client.impl.docbroker.DocbrokerClient$PreferencesObserver.update(DocbrokerClient.java:251)
at com.documentum.fc.common.impl.preferences.TypedPreferences.notifyObservers(TypedPreferences.java:559)
at com.documentum.fc.common.impl.preferences.TypedPreferences.setString(TypedPreferences.java:168)
at com.gsk.rd.datacoe.dataspider.FetchDocumentumStats.connectToDocumentum(FetchDocumentumStats.java:357)
at com.gsk.rd.datacoe.dataspider.FetchDocumentumStats.run(FetchDocumentumStats.java:92)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Please can anyone help me. I am new to documentum.
From my experience, it is best to use the IDfClientX interface and work your way from there. Perhaps this example will help you:
// This is just an example. You might want to encapsulate this functionality in a class of your own
import com.documentum.com.DfClientX;
import com.documentum.com.IDfClientX;
import com.documentum.fc.client.IDfClient;
import com.documentum.fc.client.IDfSession;
import com.documentum.fc.client.IDfSessionManager;
import com.documentum.fc.client.IDfTypedObject;
import com.documentum.fc.common.DfException;
import com.documentum.fc.common.IDfLoginInfo;
public class Main {
public static void main(String[] args) throws DfException {
IDfClientX clientX = new DfClientX();
IDfClient client = clientX.getLocalClient();
IDfTypedObject clientConfig = client.getClientConfig();
IDfLoginInfo loginInfo = clientX.getLoginInfo();
IDfSessionManager sessionManager = client.newSessionManager();
IDfSession session = connect(clientConfig, loginInfo, sessionManager, "<your host here>", 1489, "<your docbase here>", "<your username here>", "<your password here>");
// Do something with session
}
public static IDfSession connect(IDfTypedObject clientConfig, IDfLoginInfo loginInfo, IDfSessionManager sessionManager, String host, int port, String docbase, String user, String password) throws DfException {
clientConfig.setString("primary_host", host);
clientConfig.setInt("primary_port", port);
loginInfo.setUser(user);
loginInfo.setPassword(password);
sessionManager.clearIdentities();
sessionManager.setIdentity(docbase, loginInfo);
return sessionManager.getSession(docbase);
}
}

com.jcraft.jsch.JSchException: Auth fail error

Trying to connect to a host using ssh key auth. Below is my code:
package com.mkyong.common;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
/**
*
*/
public class UserAuthPubKey {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
try {
JSch jsch = new JSch();
String user = "XXXXXXXX";
String host = "XXXXXXXX.XXXXXXX.com";
int port = 22;
String privateKey = "~/.ssh/WF_OPENSSH.ppk";
String passphrase = "XXXXXXXXXXX";
jsch.addIdentity(privateKey,passphrase);
System.out.println("identity added ");
Session session = jsch.getSession(user, host, port);
System.out.println("session created.");
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
System.out.println("session connected.....");
Channel channel = session.openChannel("sftp");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect();
System.out.println("shell channel connected....");
ChannelSftp c = (ChannelSftp) channel;
// String fileName = "test.txt";
// c.put(fileName, "./in/");
// c.exit();
// System.out.println("done");
} catch (Exception e) {
System.err.println(e);
}
}
}
what change should i make here. On debugging the error seems to occur at session.connect(); statement. I am using a private key and a passphrase to connect.
String privateKey = "~/.ssh/WF_OPENSSH.ppk";
Is that a PuTTY-format keyfile? Was it generated from puttygen, the PuTTY key generation utility? Jsch only reads OpenSSH-format key files, not PuTTY-format files.
You can use puttygen to convert the key to OpenSSH format if you want to use that key. See this question.
Get the lastest version of JSch. The old version shows Auth Fail for no reason

How to interact with the script after its execution using Jsch

Scenario:
1.I am able to execute a bash script on remote ssh server successfully.
2.The script wants the user to enter some input's to proceed.
The Program hangs after the script is executed.
Q:1 Is this possible using JSCH or any other java based libraries?
Q:2 Which is the best library in java to handle such scenario?
Below is my piece of code :
public class SshMultiCommands
{
public void execute(String u,String h,String p) throws Exception
{
JSch jsch = new JSch();
String user = u;
String host = h;
String passwd = p;
int port = 22;
Session session = jsch.getSession(user, host, port);
session.setPassword(passwd);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
Channel channel = session.openChannel("shell");
OutputStream ops = channel.getOutputStream();
channel.setOutputStream(ops,true);
((ChannelShell)channel).setPtyType("vt102");
((ChannelShell)channel).setEnv("LANG", "ja_JP.eucJP");
PrintStream ps = new PrintStream(channel.getOutputStream());
channel.connect();
Thread.sleep(1000);
InputStream input = channel.getInputStream();
//commands
ps.println("ls -l");
ps.println("bash /opt/dla.sh");
ps.println("3"); // The sample user Input to script.This is getting printed but is not getting executed
printResult(input, channel);
ps.close();
channel.disconnect();
session.disconnect();
//System.out.println("OT Session Completed");
}
private static void printResult(InputStream input,
Channel channel) throws Exception
{
int SIZE = 1024;
byte[] tmp = new byte[SIZE];
while (true)
{
while (input.available() > 0)
{
int i = input.read(tmp, 0, SIZE);
if(i < 0)
break;
System.out.print(new String(tmp, 0, i));
}
if(channel.isClosed())
{
System.out.println("exit-status: " + channel.getExitStatus());
break;
}
try
{
Thread.sleep(300);
}
catch (Exception ee)
{
}
}
}
}
Solution: Put sleep of 5-10 sec after you run the script or program. And keep flushing the output stream after every command. If you already used sleep, extend its time.
The program or script that u run takes a bit of time to take over the system's standard input and out streams. If u pass all the commands and params immediately the parameters which were intented for the program goes to the system's bash instead !

How to set a connection from eclipse to SQLServer?

I am trying to connect to SQL Server from eclipse and i get the following error. I mention that i verified and the SQL Server Browser is running on the host and i have no firewall active.
com.microsoft.sqlserver.jdbc.SQLServerException: The connection to the host
LAURA-PC, named instance sqlexpress failed. Error: "java.net.SocketTimeoutException:
Receive timed out". Verify the server and instance names and check that no firewall
is blocking UDP traffic to port 1434. For SQL Server 2005 or later, verify that
the SQL Server Browser Service is running on the host.
This is the code i've written:
import java.sql.*;
public class ConnectSQLServer {
public void connect(String url){
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
Connection connection = DriverManager.getConnection(url);
System.out.println("Connected");
Statement statement = connection.createStatement();
String query = "select * from Vehicle where Mileage < 50000";
ResultSet rs = statement.executeQuery(query);
while(rs.next()){
System.out.println(rs.getString(1));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
ConnectSQLServer connServer = new ConnectSQLServer();
String url = "jdbc:sqlserver://LAURA-PC\\SQLEXPRESS;databaseName=Register;integratedSecurity=true";
connServer.connect(url);
}
}
First thing before DB programming. Test each "step". Before executing any query or even writing any other code, please check if you can connect to the DB. I assume that you are connecting to the local db. For steps on making your connection URL, see - http://technet.microsoft.com/en-us/library/ms378428.aspx
Try changing your URL to - jdbc:sqlserver://localhost;user=Mine;password=Secret;databaseName=MyDB. I tried this code and it worked.
import java.sql.*;
public class ConnectSQLServer {
public void connect(String url){
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
Connection connection = DriverManager.getConnection(url);
System.out.println("Connected");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
ConnectSQLServer connServer = new ConnectSQLServer();
String url = "jdbc:sqlserver://localhost;user=Mine;password=Secret;databaseName=AdventureWorks";
connServer.connect(url);
}
}
Just ENABLE/START SQL Server Browser and copy sqljdbc_auth.dll file to Windows->System32 by extracting this file from ( Microsoft jdbc driver 9.2 for sql server )

StreamingNotifications not working with Office 365 / Exchange Online

I have developed a small console application to test EWS StreamingSubscriptions / Notifications. In the past we used Push Notifications but ,in theory, when using StreamingNotifications I should be able to avoid creating a listener http endpoint and all the trouble with it (firewall, etc.).
So, from my local machine; I'm doing this:
static void Main(string[] args)
{
if (String.IsNullOrEmpty(ConfigurationManager.AppSettings["PrimaryLabUserId"]))
{
throw new ArgumentNullException("Please provide a value for PrimaryLabUserId in app.config");
}
_primaryLabUserId = ConfigurationManager.AppSettings["PrimaryLabUserId"];
string ServiceAccountName = ConfigurationManager.AppSettings["ExchangeServiceAccountName"];
string ServiceAccountPassword = ConfigurationManager.AppSettings["ExchangeServiceAccountPassword"];
_service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
_service.Credentials = new WebCredentials(ServiceAccountName, ServiceAccountPassword);
_service.AutodiscoverUrl(_primaryLabUserId, (x) => true);
_ewsUrl = _service.Url.AbsoluteUri;
var _connection = new StreamingSubscriptionConnection(_service, 30);
var sub = SubscribeForStreamingNotifications();
_connection.AddSubscription(sub);
_connection.OnDisconnect +=
new StreamingSubscriptionConnection.SubscriptionErrorDelegate(OnDisconnect);
// set up subscriptions here.
_connection.OnNotificationEvent +=
new StreamingSubscriptionConnection.NotificationEventDelegate(OnNewMail);
_connection.Open();
Console.WriteLine("Listening streaming...");
Console.ReadLine();
}
public static StreamingSubscription SubscribeForStreamingNotifications()
{
var folderIds = new List<FolderId>()
{
WellKnownFolderName.Inbox,
WellKnownFolderName.Calendar
};
var eventTypes = new List<EventType>();
eventTypes.Add(EventType.NewMail);
eventTypes.Add(EventType.Deleted);
eventTypes.Add(EventType.Moved);
eventTypes.Add(EventType.Created);
eventTypes.Add(EventType.Modified);
return _service.SubscribeToStreamingNotifications(folderIds, eventTypes.ToArray());
}
private static void OnNewMail(object sender, NotificationEventArgs args)
{
var test = args;
Console.WriteLine("Incoming");
}
The Subscription initializes OK, but when I send a new mail to the LabUser nothing happens. The Notification Event never fires. I tried the same with pushnotifications and it was working (on another server with a public http endpoint for exchange to call back).
I was wondering if this might have anything to do with my local machine.
How very stupid of me. I forgot to impersonate. Since I'm calling into EWS with a service account it is of course listening on the mailbox of that account unless you specify:
_service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, _primaryLabUserId);