how to automate sending commands using SSH factory - java

I am using ssh factory to automate the logins. I have to automate logins till 4 gateways and send commands and get output's of it. I have successfully automated till 3 gateways. Now i have to fire command "telnet remote_ip" to get into the 4th gateway. Where i am using telnet sessions for this 4th gateway alone since i need to fire "telnet ip", since it is using telnet protocol over here. But for the previous 3 gateway's i've used ssh sessions. But it is not firing this "telnet ip" command. Can some1 help me regarding this?.
Below is the code, where i am trying to automate it.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Scanner;
import com.jscape.inet.ssh.Ssh;
import com.jscape.inet.ssh.SshAdapter;
import com.jscape.inet.ssh.SshConnectedEvent;
import com.jscape.inet.ssh.SshDataReceivedEvent;
import com.jscape.inet.ssh.SshDisconnectedEvent;
import com.jscape.inet.ssh.SshException;
import com.jscape.inet.ssh.SshScript;
import com.jscape.inet.ssh.SshSession;
import com.jscape.inet.ssh.SshTask;
import com.jscape.inet.ssh.connection.channels.SessionClient;
import com.jscape.inet.ssh.connection.channels.SessionRequests;
import com.jscape.inet.ssh.util.SshParameters;
import com.jscape.inet.telnet.Telnet;
import com.jscape.inet.telnet.TelnetException;
import com.jscape.inet.telnet.TelnetListener;
import com.jscape.inet.telnet.TelnetScript;
import com.jscape.inet.telnet.TelnetSession;
import com.jscape.inet.telnet.TelnetTask;
public class SshScriptTutorial extends SshAdapter {
public SshScriptTutorial() {}
public void executeSshScript(String hostname, String username, String password)
throws SshException, IOException, InterruptedException, TelnetException
{
// assumes that SSH shell prompt is ">" .. this MUST match exactly
String shellPrompt = ">";
String shellPrompt1 = ":";
// initialize and create new Ssh instance
SshParameters sshParams = new SshParameters(hostname,username,password);
Ssh ssh = new Ssh(sshParams);
// register this class to receive Ssh events
ssh.addSshListener(this);
// create new script object and bind to the given ssh object
SshScript script = new SshScript(ssh);
// add tasks to script object
script.addTask(new SshTask(shellPrompt, "show host", shellPrompt));
script.addTask(new SshTask(shellPrompt, "ssh ssgpun", shellPrompt1)); // 2nd g/w
script.addTask(new SshTask(shellPrompt1, "password", shellPrompt));
script.addTask(new SshTask(shellPrompt, "net ip", shellPrompt1)); // 3rd gateway
script.addTask(new SshTask(shellPrompt1, "username", shellPrompt1));
script.addTask(new SshTask(shellPrompt1, "password", shellPrompt));
// till this it is working
// connect to SSH server and execute script
ssh.connect();
// wait until last task is complete
while(!script.isComplete()) {
try {
Thread.sleep(500);
} catch(Exception e) {
System.err.println(e.getMessage());
}
}
// disconnect from server
// ssh.disconnect();
//**
Here i am trying to get into the last remote server using command "telnet ip" using telnet session since it is involving telnet protocol. But it is not firing this command itself. So, can anybody help me regarding this. How to do?... I have even tried using ssh sessions for this "telnet ip" and for username and pass. If i use ssh session for this 4th gateway, i am able to automate only "telnet ip" and it is asking for login name, and login name is not automated. So, i have tried both ssh sessions and telnet sessions. I dont know what is the prob or how to solve it.
Kindly help...
//**
// create new Telnet instance
Telnet telnet = new Telnet("10.228.128.33");
// create new TelnetScript instance and bind to Telnet instance
TelnetScript script_t = new TelnetScript(telnet);
// create a task that waits for login prompt and submits username
TelnetTask username_t = new TelnetTask(shellPrompt1,"switchind", shellPrompt1);
// create task that waits for password prompt and submits password
TelnetTask password_t = new TelnetTask(shellPrompt1, "Indore123", shellPrompt);
// add tasks to script
script_t.addTask(username_t);
script_t.addTask(password_t);
// connect to telnet server … script is executed automatically
telnet.connect();
}
public void connected(SshConnectedEvent event) {
System.out.println("Connected to host: " + event.getHost());
}
public void disconnected(SshDisconnectedEvent event) {
System.out.println("Disconnected from host: " + event.getHost());
}
public void dataReceived(SshDataReceivedEvent event) {
System.out.print(event.getData());
}
public static void main(String[] args)
{
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String hostname = "host_ip";
String username = "username";
System.out.print("Enter password: ");
String password = reader.readLine();
SshScriptTutorial tutorial = new SshScriptTutorial();
tutorial.executeSshScript(hostname, username, password);
} catch(Exception e) {
e.printStackTrace();
}
}
}

Related

Connect a server through another server in putty/jump server using java

I need to connect to another server after i logged into putty server using java code and I need to download files from second server after I connected. Do anyone have the code.
Once the putty server screen appears, I enter username and password then i pass the command "ssh servername" then i need to enter yes for the question appears.
Once the above done, I have to navigate to different folders and download the files to Server1.
I used the below code to connect to server1 and it connected, After that I am not sure of jumping to server 2.
I am getting the error as below when i am trying a remote server through another server. The error and code I have entered below
Error:
Exception in thread "main" com.jcraft.jsch.JSchException: connection is closed by foreign host
at com.jcraft.jsch.Session.connect(Session.java:236)
at com.jcraft.jsch.Session.connect(Session.java:150)
at putty.putty.main(putty.java:42)
Code I used:
import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;
import org.apache.commons.io.IOUtils;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
public class putty {
public static String user = "username";
public static String host = "server1.server.net";
public static String password = "Password";
public static String secondpassword = "Password";
public static String tunnelRemoteHost = "server2.server.net";
public static void main(String[] args) throws IOException, JSchException, SftpException {
StringBuilder outputBuffer = new StringBuilder();
int port = 22;
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
int forwardPort = 2222;
session.setPortForwardingL(forwardPort, tunnelRemoteHost, 22);
Session secondSession = jsch.getSession(user, "localhost", forwardPort);
secondSession.setPassword(secondpassword);
secondSession.setConfig("StrictHostKeyChecking", "no");
secondSession.connect();
session.openChannel("sftp");
// now we're connected to the secondary system
Channel channel = secondSession.openChannel("sftp");
channel.connect();
ChannelSftp channelSftp = (ChannelSftp)channel;
channel.disconnect();
session.disconnect();
System.out.print(outputBuffer.toString());
}
}
I am using latest jsch jar 0.1.55. Can someone look into and let me what I am missing here.
Try to update jsch to 0.1.55 https://mvnrepository.com/artifact/com.jcraft/jsch/0.1.55
Your current version 0.1.42 is almost 10 years old. It may not change anything or may help.
I am able to achieve what i wanted through Windows Commandline with plink command

how to bypass lotus notes password log in - JAVA code

My code works great so far, except for one part which I need to bypass somehow because this is going to be an autosys job. That one part is logging in to lotus notes (when I'm logged in and the app is still running); every time my script runs it requires the user to input his password. I've tried code to log in to my account but it still didn't work for me, so I was wondering what am I missing? Any help would be greatly appreciated! My code is below. It is very close to being finished. The popup is the only issue I have; the code below is compilable and runs just fine so far.
import java.io.IOException;
import java.util.*;
import javax.mail.*;
import javax.mail.Session;
import javax.mail.internet.*;
import javax.swing.JOptionPane;
import javax.activation.*;
import lotus.domino.*;
import lotus.notes.addins.util.DominoAddressBook;
public class SendEmail extends NotesThread {
#SuppressWarnings("deprecation")
public static void main(String [] args) throws AddressException, MessagingException {
// runs the program, mainly runNotes()
SendEmail e = new SendEmail();
e.start();
//e.sendMail();
}
public void runNotes() {
try {
// TODO: pop's up dialog box for user password to be input if password is in line 32 else its line 59
// might be because I'm creating a new session each time the program is run?
// this lets you retype the password as many times as you want until you got it correct (no password in argument, line 32)
lotus.domino.Session s = NotesFactory.createSessionWithFullAccess();
// configures so the password entered in the dialog box matches the password here (security check user)
// lotus.domino.Session s = NotesFactory.createSession((String)null, "userID", "pass!");
String p = s.getPlatform();
System.out.println("Platform: " + p);
System.out.println("Username: " + s.getUserName());
System.out.println("Server name: " + s.getServerName());
// self explantory, set's up the email with the message, attachment, etc
Database db = s.getDatabase(null, "C:\\Program Files (x86)\\IBM\\Lotus\\Notes\\Data\\names.nsf");
Document doc = db.createDocument();
doc.setSaveMessageOnSend(true);
RichTextItem attachedFile = doc.createRichTextItem("Attachment");
attachedFile.embedObject(EmbeddedObject.EMBED_ATTACHMENT, "G-Man", "C:\\Users\\F400318\\Desktop\\testDB2.xlsx", "testDB");
StringBuilder body = new StringBuilder();
body.append("This email is a test!");
doc.appendItemValue("\n\n");
doc.appendItemValue("Body", body.toString());
doc.appendItemValue("Subject", "Test E-Mail");
doc.appendItemValue("Sent", "user#emailcompany.com");
doc.send("user#emailcompany.com");
System.out.println("Check email... it should have been sent");
} catch (Exception e) {
e.printStackTrace();
}
}
Where is your code running? On a Domino server, from a Notes client, or outside of Notes/Domino entirely?
The createSessionWithFullAccess() method assumes the code is running on the server and it will prompt for the password when needed unless you pass the password as an argument createSessionWithFullAccess("password").
http://www-12.lotus.com/ldd/doc/domino_notes/rnext/help6_designer.nsf/b3266a3c17f9bb7085256b870069c0a9/5a8f8afb89d617f785256c54004d9eb4?OpenDocument
* Edit *
From the looks of your code, you're trying to create a Swing application with JOptionPane, so using createSessionWithFullAccess() isn't necessary from the Notes client. You could just use NotesFactory.createSession() and it will use the users's Notes ID for credentials. Another option you could consider is if you're calling your code from a Notes agent, then you could pass the Session created by the agent to your code instead of creating a new one.

Having trouble connecting android with MQTT to broker

I am trying to connect to an Apollo broker, this code works perfectly when I use it alone in a normal java project, everything is exactly the the same except now its in an android project and i try to run it when i click a button from MainActivity.
I have a text box that gets updated to "1" before i try to connect MQttClient however the second .setT("2") does not get run so I think the problem is with client.connect(opts) as if i just do client.connect() the text box gets updated to "2" but since i need the username and password it from opts the rest does not run
Just started using MQTT learning as I go along. Thanks for any help.
package com.example.androidmqtt;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.eclipse.paho.client.mqttv3.internal.MemoryPersistence;
public class Service {
MqttClient client;
MemoryPersistence persistence = new MemoryPersistence();
public Service()throws Exception{}
public static void main(String[] args) throws Exception {
new Service().doDemo();
}
public void doDemo() {
try {
client = new MqttClient("tcp://10.1.10.1:1883", "testingMyMQTT", persistence);
MainActivity.setT("2");
MqttConnectOptions opts = new MqttConnectOptions();
opts.setUserName("nabi");
opts.setPassword("M4rk3".toCharArray());
opts.setKeepAliveInterval(480);
MainActivity.setT("1");//sets the txt1 in main view to 1 so i know whats going on
client.connect(opts);
MainActivity.setT("2");
MqttMessage msg = new MqttMessage("Works".getBytes());
msg.setRetained(true);
msg.setQos(1);
MainActivity.setT("its working");
MqttTopic topic = client.getTopic("Android/Test");
MqttDeliveryToken token = topic.publish(msg);
} catch (MqttException e) {
e.printStackTrace();
}
}
}
Verify that android can connect to your local network 10.1.10.1 and if so, check the logs of the Apollo broker.

How to pass username and password in the localhost url to connect with the memcached in Java?

Hi, I want to pass the username and password to connect to localhost where I have deployed memcached.
Here is my code.
import java.io.IOException;
import java.net.InetSocketAddress;
import net.spy.memcached.MemcachedClient;
public class MemCaheConnection {
public void ConnectMemCaheConnection() throws IOException{
MemcachedClient c = new MemcachedClient(new InetSocketAddress("localhost", 11211));
c.flush();
}
}
Can anyone help?
without explicit use of http://code.google.com/p/memcached/wiki/SASLAuthProtocol there is no need for username+password, did you check the service is running on port 11211?

How to programmatically put data to the Google Appengine database from remote executable?

I would like to pre-fill and periodically put data to the Google Appengine database.
I would like to write a program in java and python that connect to my GAE service and upload data to my database.
How can I do that?
Thanks
Please use RemoteAPI for doing this programmatically.
In python, you can first configure the appengine_console.py as described here
Once you have that, you can launch and write the following commands in the python shell:
$ python appengine_console.py yourapp
>>> import yourdbmodelclassnamehere
>>> m = yourmodelclassnamehere(x='',y='')
>>> m.put()
And here is code from the java version which is self explanatory (directly borrowed from the remote api page on gae docs):
package remoteapiexample;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.tools.remoteapi.RemoteApiInstaller;
import com.google.appengine.tools.remoteapi.RemoteApiOptions;
import java.io.IOException;
public class RemoteApiExample {
public static void main(String[] args) throws IOException {
String username = System.console().readLine("username: ");
String password =
new String(System.console().readPassword("password: "));
RemoteApiOptions options = new RemoteApiOptions()
.server("<your app>.appspot.com", 443)
.credentials(username, password);
RemoteApiInstaller installer = new RemoteApiInstaller();
installer.install(options);
try {
DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
System.out.println("Key of new entity is " +
ds.put(new Entity("Hello Remote API!")));
} finally {
installer.uninstall();
}
}
}

Categories