Ganymede SSH: Executing multiple commands in a single session. The Easy Way

Download the Ganymede ssh jar from www.ganymed.ethz.ch/ssh2/



The below given program acts as if you are working with putty console. The text in bold are doing the input and output work. With the given format of the program, it is highly customizable.

The program goes like this:-



import java.awt.Color;import java.awt.FlowLayout;import java.awt.Font;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import java.io.BufferedReader;import java.io.File;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.util.Scanner;import javax.swing.BoxLayout;import javax.swing.JButton;import javax.swing.JDialog;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JPasswordField;import javax.swing.JTextArea;import javax.swing.JTextField;import javax.swing.SwingUtilities;

import ch.ethz.ssh2.Connection;import ch.ethz.ssh2.InteractiveCallback;import ch.ethz.ssh2.KnownHosts;import ch.ethz.ssh2.ServerHostKeyVerifier;import ch.ethz.ssh2.Session;import ch.ethz.ssh2.StreamGobbler;

 class MySessionConnector extends Thread { String hostname; String username;
InputStream in =null; OutputStream out =null; InputStream err = null;   public static void main(String[] args)   {   new MySessionConnector();   } public MySessionConnector() { this.hostname = "server"; this.username = "user"; String password = "password"; try { /* Create a connection instance */
Connection conn = new Connection(hostname); /* Now connect */ conn.connect(); boolean isAuthenticated = conn.authenticateWithPassword(username, password); if (isAuthenticated == false) throw new IOException("Authentication failed."); /* Create a session */
Session sess = conn.openSession(); sess.requestPTY("dumb", 90, 30, 0, 0, null); sess.startShell(); Scanner scan = new Scanner(System.in); String myinput = null; in = sess.getStdout(); out = sess.getStdin(); err = sess.getStderr(); String myCommand = null; //new RemoteErrorConsumer().start(); new RemoteConsumer().start(); char[] carr = null; while(!(myCommand = scan.nextLine()).equalsIgnoreCase("Exit")) { carr = myCommand.toCharArray() ; for(int i=0;i<carr.length;i++) { out.write(carr[i]); } out.write(13); } } catch(Exception e1) { e1.printStackTrace(); } }//Constructor Ends


class RemoteConsumer extends Thread { public void run() { try{ byte[] buff = new byte[8192]; int len = 0; int i=0; while (true) { len = in.read(buff); for(i=0;i<len;i++) { System.out.print((char)buff[i]); }    }
} catch(Exception e1) { e1.printStackTrace(); } }//run ends }//class RemoteConsumer Ends class RemoteErrorConsumer extends Thread {        public void run()        {         try{ byte[] buff = new byte[8192]; int len = 0; int i=0; while (true) { len = err.read(buff); for(i=0;i<len;i++) { System.out.print((char)buff[i]); }    }
} catch(Exception e1) { e1.printStackTrace(); }        } } }

PHP



PHP Fundas:-


LEARNING PHP


So here it goes, the PHP tutorial:-




1) PHP is a server side scripting language.


2) It initially stood  for "personal Home Page", but now it is known the world over as, "PHP Hypertext Preprocessor".


3) Its a very easy language to learn.


4) The first step is that you should get some php editor (or notepad will also do :) ), mySql(the most frequently used database with php) and apache web-server configured on your machine.


5) Now, the XAMPP is eaily available here: - http://www.apachefriends.org/en/xampp.html


6) XAMPP offers a very good control panel application, which greatly simplifies your work of PHP programming, sql database handling and deployment and running the application.


7) PHP language basics:-


A sample PHP program:-




<!DOCTYPE html>
<html lang="en">
<head><title>Today's Date</title></head>
<body>
Today's day according to the web server is 
<p>
<?php
echo date('l');


?>
</p>
</body>
</html>




here, whatever that comes between the tags <? and > is interpreted by the php engine, while the server is serving to the browser request, asking for this page.


And, the apache server is capable of doing this.


8) A PHP statement ends with a semi colon.


echo "Hello World";


9) Comments in PHP:-
Use // or /**/




10) PHP variable:-


--The normal rules of variable name apply here. That is, it should start with an alphabet or underscore....etc.
--Also, in PHP, we don't  declare variables, before using them. We simply go ahead and use them.




Eg:-


$myCar="Volvo";


After this, the variable named myCar has the value "Volvo".






--PHP automatically converts the variable to the correct data type, depending on its value.
--Also, while referring to the variable, we precede the variable name with a $ sign.
--The general variable scope rules that make common sense are also applicable in PHP.


--One important example:-


Local Scope Variables:-


<?php
$a = 5; // global scope


function myTest()
{
echo $a; // local scope



myTest();
?>




This program will output blanks, as the $a used in the function is taken to be of local scope, is one created in the function itself.


--To tell the php engine that we are going to refer to the gobal scope variables, this is what we do in a program:-


<?php
$a = 5;
$b = 10;


function myTest()
{
global $a, $b; // This is what we do !!!!!!!!
$b = $a + $b;



myTest();
echo $b;
?>




--PHP also stores all global variables in an array called $GLOBALS[index]. Its index is the name of the variable. This array is also accessible from within functions and can be used to update global variables directly.


Eg:-


<?php
$a = 5;
$b = 10;


function myTest()
{
$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];



myTest();
echo $b;
?>




11) Static variable declaration:-


static $rememberMe;


12) 




x) Variables passed in forms can also be caught in PHP. Well.... I am not assuming anything about my readers, and hence I am mentioning everything at its face-value. I say this, because, the function that I just described, is the most primitive stuff, any server side scripting language is expected to do. :)


y) Lets see an example, where in we will have two web pages. The one , a html page having a simple form and the other being a PHP page called from the first one and which will utilize the passed up variables for some random purpose, like printing a welcome message.


z)  The corresponding PHP page that aims to say hello with you name is:-




<?php
$firstName = $_GET['firstname'];
$lastName = $_GET['lastname'];
echo 'Welcome to our website, ' .
htmlspecialchars($firstName, ENT_QUOTES, 'UTF-8') . ' ' .
htmlspecialchars($lastName, ENT_QUOTES, 'UTF-8') . '!';
?>














---------------------------------------------------------------------------------------------------
Some genral PHP funda from O'Reiley Publications book


Web 1.0 : Simple HTML pages as envisaged by Tim Berner's Lee.


Web 1.1 : Advent of  Java Script , JScipt (Tweaked version of java script by Microsoft). On the server side, we had CGI+Perl and PHP+MySQL primarily.


Web 2.0 : When PHP allies with MySQL to store and retrieve this data, you have the fundamental parts required for the development of social networking sites and the beginnings of Web 2.0.






With PHP, it’s a simple matter to embed dynamic activity in web pages. When you give pages the .php extension, they have instant access to the scripting language. From a developer’s point of view, all you have to do is write code such as the following:




<?php
echo "Hello World. Today is ".date("l").". ";
?>




Output:-
Hello World. Today is Thursday.


PHP enabled web-servers have actually got a PHP interpreter with them. Eg. Apache






--Using PHP, you have unlimited control over your web server. Whether you need to modify HTML on the fly, process a credit card, add user details to a database, or fetch information from a third-party website, you can do it all from within the same PHP files in which the HTML itself resides.




-- PHP is vastly complemented by MYSQL and JavaScript.


let’s take a quick look at how you can use basic JavaScript, accepted by all
browsers:


<script type="text/javascript">
document.write("Hello World. Today is " + Date() );
</script>




The result will look something like this:


Hello World. Today is Sun Jan 01 2012 14:14:00




** It’s worth knowing that unless you need to specify an exact version of
JavaScript, you can normally omit the type="text/javascript" and just
use <script> to start the interpretation of the JavaScript.




As previously mentioned, JavaScript was originally developed to offer dynamic control over the various elements within an HTML document, and that is still its main use. But more and more, JavaScript is being used for Ajax. This is a term for the process of accessing the web server in the background.




***
Ajax is the main process behind what is now known as Web 2.0 (a term coined by Tim O’Reilly, the founder and CEO of this book’s publishing company), in which web pages have started to resemble standalone programs, because they don’t have to be reloaded in their entirety. Instead, a quick Ajax call can pull in and update a single element on a web page, such as changing your photograph on a social networking site or replacing a button that you click with the answer to a question.


***
Some common PHP syntax  examples:-


$username = "Fred Smith";//String


$count = 17;//integer


$team = array('Bill', 'Joe', 'Mike', 'Chris', 'Jim');//array


$oxo = array(array('x', '', 'o'),
array('o', 'o', 'x'),
array('x', 'o', '' ));


echo $username;
echo $count;
echo $team[3]; // Displays the name Chris
echo $oxo[1][2];






**
In PHP, Variable names are case-sensitive.


**
Logical Operators in PHP:-


if ($hour > 12 && $hour < 14) dolunch();






**
Variable Assignement
$x += 10;
$y -= 10;
++$x;
--$y;


**
String Concatenation


String concatenation
String concatenation uses the period (.) to append one string of characters to another.
The simplest way to do this is as follows:




echo "You have " . $msgs . " messages.";




Just as you can add a value to a numeric variable with the += operator, you can append one string to another using .= like this:


$bulletin .= $newsflash;






**
String Types in PHP : Under Single Quotes , Under Double Quotes:-


PHP supports two types of strings that are denoted by the type of quotation mark that you use. If you wish to assign a literal string, preserving the exact contents, you should use the single quotation mark (apostrophe) like this:




$info = 'Preface variables with a $ like this: $variable';


In this case, every character within the single-quoted string is assigned to $info. 


If you had used double quotes, PHP would have attempted to evaluate $variable as a variable. On the other hand, when you want to include the value of a variable inside a string, you do so by using double-quoted strings:




echo "There have been $count presidents of the US";






**
Using Escape Characters in Strings:-




$text = 'My sister's car is a Ford'; // Erroneous syntax


$text = 'My sister\'s car is a Ford';//Correct Usage






**
Variable Typing:-


PHP is a very loosely typed language. This means that variables do not have to be declared before they are used, and that PHP always converts variables to the type required by their context when they are accessed.




Example 3-10. Automatic conversion from a number to a string


<?php
$number = 12345 * 67890;
echo substr($number, 3, 1);
?>






At the point of the assignment, $number is a numeric variable. But on the second line, a call is placed to the PHP function substr, which asks for one character to be returned from $number, starting at the fourth position (remembering that PHP offsets start from zero). To do this, PHP turns $number into a nine-character string, so that substr can access it and return the character, which in this case is 1.




The same goes for turning a string into a number and so on.




**Constants
Constants are similar to variables, holding information to be accessed later,  except that they are what they sound like—constant. In other words, once you have defined one, its value is set for the remainder of the program and cannot be altered.




define("ROOT_LOCATION", "/usr/local/www/");


Then to read the contents of the variable:-


$directory = ROOT_LOCATION;





The main two things you have to remember about constants are that
they must not be prefaced with a $ sign (as with regular variables), and 
that you can define them only using the define function.