Connect to unix server through java

Hi All,
I've seen this topic being discussed here, but I want to clarify my situation.
I'm a college student, so our school provides us accounts to a unix server.
I am writing a java program that needs to connect to this unix server owned by the school, and run some commands and obtain the results and display them in the same java program.
for example after the connection, I use the java Runtime() method to pass the "pwd" command from my program, and my java program should receive the result something like "/university/student/program" from the server, and I should be able to display in the java program.
I feel like since the unix from school is already acting as a "server," I don't need to write the server side code, it should be handled by the unix system, right?
Can someone give me a sample code on how to establish such connection?
BTW, I usually use ssh to access the unix server.
Much appreciated, and it's kinda urgent.
Thank You.

There are ssh clients written in Java so I'm not really sure you really want the following code because it accesses ssh using Runtime.exec(). I have never used this with anything except Linux so I assume that your client ssh is in a directory that is on the PATH.
If your server ssh is set up to do public key authentication then you will not have to supply the user password. If you do require a password then on Linux FC5 you will be prompted though a dialog. I don't know how you provide the password in Windows.
import java.io.*;
public class Fred117_1
    static class AsyncPipe implements Runnable
        public AsyncPipe(InputStream istrm, OutputStream ostrm)
            istrm_ = istrm;
            ostrm_= ostrm;
        public void run()
            try
                final byte[] buffer = new byte[1024];
                for (int length = 0; (length = istrm_.read(buffer)) != -1;)
                    ostrm_.write(buffer, 0, length);
            catch (Exception e)
                e.printStackTrace();
        private final OutputStream ostrm_;
        private final InputStream istrm_;
    public static void main(String[] args) throws Exception
        final boolean isWindows = System.getProperty("os.name").startsWith("Windows");
        final String LINE_SEPARATOR = System.getProperty("line.separator");
        final Process process = Runtime.getRuntime().exec(isWindows ? "cmd.exe" : "sh");
        new Thread(new AsyncPipe(process.getErrorStream(), System.err)).start();
        new Thread(new AsyncPipe(process.getInputStream(), System.out)).start();
        final Writer writer = new OutputStreamWriter(process.getOutputStream(), "UTF-8");
        final String[] shCommands =
            "ssh alpha",
            "df -k",
            "ls",
        for (String shCommand : shCommands)
            System.out.println(shCommand);
            writer.write(shCommand);
            writer.write(LINE_SEPARATOR);
        writer.close();
        final int returnCode = process.waitFor();
        System.out.println("Return code = " + returnCode);
}

Similar Messages

  • Need to access/connect Remote Unix server from Java

    Please any one give me a direct solution for connecting a remote Unix server through telnet connection from java application. Thanks in advance..

    If I run the below program codes, in the console it is asking to enter username and password in manual but I need to give it automatically.
    The highlighted "root" is entered by the user manually using keyboard.
    Expected:
    I mean the username, password and some action is set to be automatic, so that it should not ask the user to enter the input from keyboard.
    import java.awt.Robot;
    import java.awt.event.KeyEvent;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import org.apache.commons.net.telnet.TelnetClient;
    import org.apache.commons.net.telnet.TelnetNotificationHandler;
    import org.apache.commons.net.telnet.SimpleOptionHandler;
    import org.apache.commons.net.telnet.EchoOptionHandler;
    import org.apache.commons.net.telnet.TerminalTypeOptionHandler;
    import org.apache.commons.net.telnet.SuppressGAOptionHandler;
    import org.apache.commons.net.telnet.InvalidTelnetOptionException;
    import java.util.StringTokenizer;
    * This is a simple example of use of TelnetClient.
    * An external option handler (SimpleTelnetOptionHandler) is used.
    * Initial configuration requested by TelnetClient will be:
    * WILL ECHO, WILL SUPPR
    * ESS-GA, DO SUPPRESS-GA.
    * VT100 terminal type will be subnegotiated.
    * <p>
    * Also, use of the sendAYT(), getLocalOptionState(), getRemoteOptionState()
    * is demonstrated.
    * When connected, type AYT to send an AYT command to the server and see
    * the result.
    * Type OPT to see a report of the state of the first 25 options.
    * <p>
    * @author Bruno D'Avanzo
    public class UnixConnect implements Runnable, TelnetNotificationHandler
        static TelnetClient tc = null;
         * Main for the TelnetClientExample.
        public static void main(String[] args) throws IOException
            FileOutputStream fout = null;
            /*if(args.length < 1)
                System.err.println("Usage: TelnetClientExample1 <remote-ip> [<remote-port>]");
                System.exit(1);
            String remoteip = "192.168.20.11";
            int remoteport;
            if (args.length > 1)
                remoteport = (new Integer(args[1])).intValue();
            else
                remoteport = 23;
            try
                fout = new FileOutputStream ("spy.log", true);
            catch (Exception e)
                System.err.println(
                    "Exception while opening the spy file: "
                    + e.getMessage());
            tc = new TelnetClient();
            TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT200", false, false, true, false);
            EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false);
            SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true);
            try
                tc.addOptionHandler(ttopt);
                tc.addOptionHandler(echoopt);
                tc.addOptionHandler(gaopt);
            catch (InvalidTelnetOptionException e)
                System.err.println("Error registering option handlers: " + e.getMessage());
            while (true)
                boolean end_loop = false;
                try
                    tc.connect(remoteip, remoteport);
                    Thread reader = new Thread (new UnixConnect());
                    tc.registerNotifHandler(new UnixConnect());
                    reader.start();
                    OutputStream outstr = tc.getOutputStream();
                    byte[] buff = new byte[1024];
                    int ret_read = 0;
                    do
                        try
                            ret_read = System.in.read(buff);
                            if(ret_read > 0)
                            outstr.write(buff, 0 , ret_read);
                            outstr.flush();
                        catch (Exception e)
                            System.err.println("Exception while reading keyboard:" + e.getMessage());
                            end_loop = true;
                    while((ret_read > 0) && (end_loop == false));
                    try
                        tc.disconnect();
                    catch (Exception e)
                              System.err.println("Exception while connecting:" + e.getMessage());
                catch (Exception e)
                        System.err.println("Exception while connecting:" + e.getMessage());
                        System.exit(1);
         * Callback method called when TelnetClient receives an option
         * negotiation command.
         * <p>
         * @param negotiation_code - type of negotiation command received
         * (RECEIVED_DO, RECEIVED_DONT, RECEIVED_WILL, RECEIVED_WONT)
         * <p>
         * @param option_code - code of the option negotiated
         * <p>
        public void receivedNegotiation(int negotiation_code, int option_code)
            String command = null;
            if(negotiation_code == TelnetNotificationHandler.RECEIVED_DO)
                command = "DO";
            else if(negotiation_code == TelnetNotificationHandler.RECEIVED_DONT)
                command = "DONT";
            else if(negotiation_code == TelnetNotificationHandler.RECEIVED_WILL)
                command = "WILL";
            else if(negotiation_code == TelnetNotificationHandler.RECEIVED_WONT)
                command = "WONT";
            System.out.println("Received " + command + " for option code " + option_code);
         * Reader thread.
         * Reads lines from the TelnetClient and echoes them
         * on the screen.
        public void run()
            InputStream instr = tc.getInputStream();
            try
                byte[] buff = new byte[1024];
                int ret_read = 0;
                do
                    ret_read = instr.read(buff);
                    if(ret_read > 0)
                       System.out.print(new String(buff, 0, ret_read));
                while (ret_read >= 0);
            catch (Exception e)
                System.err.println("Exception while reading socket:" + e.getMessage());
            try
                tc.disconnect();
            catch (Exception e)
                System.err.println("Exception while closing telnet:" + e.getMessage());

  • Getting problem when connecting to SMTP server through java code

    Hi all,
    I am getting problem when i am going to connect with "Kerio SMTP server" through java code. The error what i am getting is :
    "[16/Sep/2008 15:59:09] Sent: Queue-ID: 48cf8a73-000000f9, Recipient: <[email protected]>, Result: failed, Status: 5.3.2 554 5.0.0 Too many hops (101, max 100), message looping" when sending an email from [email protected]

    Looks like something is set up wrong on your server that's causing messages
    to be forwarded around a loop too many times without ever reaching the destination.
    For instance, if server A forwards to server B, and server B forwards to server A,
    this would happen.

  • How do i connect to sql server using java?

    hi ever body
    i need to connect to sql server using java
    what is the driver i will use?
    thanks

    Microsoft make a jdbc driver and it is readily available through MSDN. Here is a link http://msdn2.microsoft.com/en-us/data/aa937724.aspx. Whatever jdbc driver you are looking for, Google it, and if it exists you'll find it in 10 seconds.

  • Problem in executing a unix command through java

    hi
    i'm trying to execute unix command through java
    simple shell command like "ls -l >test " but i'm not able to see the result.
    there are no error messages.
    Code is:
    import java.lang.Runtime.*;
    class ExecDemo
         public static void main(String[] args)
              Runtime r=Runtime.getRuntime();
              Process p=null;
              try
                   p=r.exec("ls -l > test");
              catch (Exception e)
                   System.out.println("Error executing nedit.");
    }can anyone help please.

    get the the inputStream of the runtime object after executing the command.
    now use the readLine() function until it becomes null.
    egs: with reference to ur code.
    InputStream is=p.getInputStream()
    while(is!=null)
    String s=is.readLine();
    if the command don't execute try giving the full path also like /sbin/ls -l

  • ERROR#: 2002 can't connect to MySQL server through socket '/var/mysql/mysql.sock'

    I was following this adobe article (
    http://www.adobe.com/devnet/dreamweaver/articles/php_macintosh.html)
    to set up PHP and MySQL and connect a MySQL database to dreamweaver
    in Mac OS 10.4.8 and I kept getting:
    "Can't connect to MySQL server through socket
    '/var/mysql/mysql.sock' ERROR#: 2002".
    After a lot of searching I came across
    this
    article which said that there was an error in the PHP and MySQL
    connection or something.
    Anyway all I had to do was type (in a TERMINAL window):
    $ sudo mkdir /var/mysql
    $ sudo ln -s /tmp/mysql.sock /var/mysql/mysql.sock
    and that fixed the problem, otherwise the adobe article
    worked very well.
    Check out the "this article" link to get the fix straight
    from the horse's mouth.

    I was following this adobe article (
    http://www.adobe.com/devnet/dreamweaver/articles/php_macintosh.html)
    to set up PHP and MySQL and connect a MySQL database to dreamweaver
    in Mac OS 10.4.8 and I kept getting:
    "Can't connect to MySQL server through socket
    '/var/mysql/mysql.sock' ERROR#: 2002".
    After a lot of searching I came across
    this
    article which said that there was an error in the PHP and MySQL
    connection or something.
    Anyway all I had to do was type (in a TERMINAL window):
    $ sudo mkdir /var/mysql
    $ sudo ln -s /tmp/mysql.sock /var/mysql/mysql.sock
    and that fixed the problem, otherwise the adobe article
    worked very well.
    Check out the "this article" link to get the fix straight
    from the horse's mouth.

  • Connectiong to Exchange Server through JAVA

    Hi friends,
    I am new to java mail.i have a problem with connecting to exchange server thru java. my java program sends a mail.but i want to get an alert when ever received a mail and also download the mail to local disk from exchange server.
    so if you can please help me.Reply to this ,send me the links or sample codes / paste here itself.
    Advance Thanks,
    Sankar.P

    Hi friends,
    I am new to java mail.i have a problem with connecting to exchange server thru java. my java program sends a mail.but i want to get an alert when ever received a mail and also download the mail to local disk from exchange server.
    so if you can please help me.Reply to this ,send me the links or sample codes / paste here itself.
    Advance Thanks,
    Sankar.P

  • How to track IP's of clients connecting to DB server through Apps Server

    My Application server address is like http://192.220.0.75:7779/forms90/f90servlet form=TEST.fmx&userid=@abc
    I can connect to Apps server from any computer using explorer with this address .
    for auditing when I connect to db server through Apps server then my audit table detect only server IP- 192.220.0.75 each time but when I connect by oracle DS or toad then my audit table detect each computers defferent IP address.
    how can I detect different users and IP addresses connecting to database server using apps server instead of apps server IP?

    You can try to use WebCache event_log, this one will show your clients IP or you can uncomment UseWebCacheIP ON in httpd.conf file, so you ensure that the access_log show the ip of the user and not of the server.
    Greetings.

  • Acessing cisco iso server through java

    Hi All,I am trying to access cisco iso server through java but i am getting timeout exception in program i am creating a client object pass all the parameter.it seems my program no is not registered.so anybody give any suggestion
    Posted by WebUser Tubu Mohanty from Cisco Support Community App

    After trying to resolve the issue Cisco TAC sen the following message:
    I will proceed to open a task with my escalation Team. As well I find this,
    http://www.cisco.com/en/US/products/hw/vpndevc/ps2284/prod_release_note09186a00804ceedf.html#wp521096
    Look after CSCec78536
    "WebVPN does not support Java applets that generate http requests. For example, you cannot login to the CiscoSecure ACS application because of this. "
    If anyone has any additional information please post. We are running into more and more prospects/clients using WebVPN approach (w/ out SSL VPN) for providing remote application access.
    Regards,
    -Murat

  • IPhone connection with B1i Server through internet

    Dear All,
    iPhone is successfully connected with my B1i server through intranet (wifi connection).
    But When i am trying to connect my B1i server through internet, I am getting the following issue.
    I am getting an error as follows when i try to browse the tomcat homepage in IE
    XCL198 HTTP-access currently not allowed from remote clients, as B1iP runs in local-mode or safe-mode.
    I followed the solution given in B1iC troubleshooting Guide.
    I am using SAP 8.81 patch level 6.
    Maintenance->CFG Runtime parameters as
    B1i Http port :8080
    B1i Https port : 8443
    B1i Server : My server ip
    Please help me to resolve this problem.

    Ken, George, Dear all,
    in given context of problems running the mobile solution, please do NOT change B1i server Xcellerator properties at all.
    Quite frequently there are ideas to change the default settings of WebDAV and remote settings of B1i server. This is simply a waste of time and definitely not required for troubleshooting or making the mobile
    solution working.
    Simply check the documentation 'Administrator's Guide for the Integration Component' for the purpose, the default settings, and further info about these properties you instruct to change:
    a) About xcl.http.localOnly
    Administrative Web access is limited to the local machine only. After installation, it is possible to manually allow access by remote machines by changing the particular setting in the operating system configuration file
    (Xcellerator.cfg).
    For additional documentation, choose Start → All Programs → Integration solution for SAP Business One → Integration framework, and then choose Help → Ref 04 – Operations, chapter 6.2.
    b) About WebDAV-based access
    WebDAV-based access to BizStore content is disabled. SAP does not recommend enabling this kind of access for productive systems, as this is typically needed for development systems only.
    For additional documentation, choose Start → All Programs → Integration solution for SAP Business One → Integration framework, then go to Help → Ref 01 – Dev Environment, chapter 3.
    For checking the connectivity from mobile to server / excluding network issues, B1iP can definitely run in local mode. When calling the server from mobile, B1iP would give you a fully sufficient, proper
    response:
    SAP B1iP detected an error: Emitted HTTP-Code 403 - Forbidden
    Internal Reason XCL198 HTTP-access currently not allowed from remote clients, as B1iP runs in local-mode or safe-mode.
    - This is exactely the alleged 'error', Tamizharasi mentioned at the beginning. Behind the internet connection issue from iPhone to his B1i server (which was unfortunately not described at all) must have been a quite different root cause - changing xcellerator properties is unfortunately a wrong recommendation here in order to clear such general iPhone issue.
    I am concerned here from security side, such settings may not be amended lightly, and lead the problem-solving in the wrong direction - beside your additional efforts.
    We do recommend to keep the default values and undo such configuration changes again, if not needed.
    For troubleshooting the mobile solution please check SAP note 1602674.
    Best regards, peter

  • Connection to a Unix-Server with Java

    Hi!
    I've got a little problem! I must write a java programm that connects to a unix-server! The programm should connect to the server and writes a command like "ls"! How can I do this? Can someone help me?
    Thanks Flyer2004

    Hi,
    something to help you with your assignment.
    The code below will connect to a server on a port.
    public void run() {
    try
    Socket socket = new Socket( "abc.com" , 13312 );
    System.out.println( "Connected to the server" );
    PrintWriter pw = new PrintWriter( socket.getOutputStream(), true );
    BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in) );
    BufferedReader in = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );
    String userInput;
    while ( (userInput = stdIn.readLine()) != null ) {
    pw.println( userInput );
    System.out.println("echo: " + in.readLine() );
    catch ( Exception ex )
    ex.printStackTrace();     
    you can use this code to connect to a port.
    now comes the server part.....
    ServerSocket serverSocket = new ServerSocket( 7777 );
    FileInputStream fis = new FileInputStream( "test.dat" );
    Socket socket = serverSocket.accept();
    OutputStream os = socket.getOutputStream();
    byte[] buffer = new byte[1024];
    int bytes = 0 ;
    int i = 0 ;
    while( ( bytes = fis.read( buffer ) ) != -1 ) {
    os.write( buffer, 0, bytes );
    os.flush();
    i++ ;
    System.out.println( "bytes sent : " + i + " KB " ) ;
    os.close();
    fis.close();
    The code above post's the file back...
    in your case you want the output of your command so use "Runtime.runexec" and run your command on the server..
    use the above code and replace the file downloading part with your code....
    send back the output of the same to the client...
    just in case ...
    if you want to do any random commands... you need to let your server knwo that and the code for that needs to be persent on the system.
    by the way this is pure vanilla and it needs to be modified a lot.
    Regards,
    myraid

  • Connecting unix server using java/jsp

    Hi ALL,
    Could you please give me solution ,I want to connect unix server from jsp and I want to run one .ksp file from jsp file

    Define "connect".
    Define "run".

  • GETTING THE OUPUT OF UNIX COMMAND THROUGH JAVA

    Hi Guyz...
    Please help me in the below code...
    My intention is to print the output of Unix command through a java program.
    The Java program resides in the Unix Server only.
    I have written the below java code , but its not returning any values....
    String s1= "ls -lt $APPL_TOP/patch/115/odf/jtfgh.odf";
    Runtime r = Runtime.getRuntime();
    Process p= r.exec(s1);
    StringBuffer ret=new StringBuffer();
    InputStream in = p.getInputStream();
    int c;     
    while ((c = in.read()) != -1)
    {                  ret.append((char)c);       
    }     in.close();
    out.println("OTUPUT : "+ ret.toString());
    Can you please help me in this by debugging the existing code or giving me the exact code??
    IT IS URGENT FOR MY PROJECT!!!!!!!!!!!!!!!!!!!!!!!!!!!
    PLEASE HELP ME!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    Since you are expecting the shell to expand the environment variable you need to use
    String[] s1= {"sh","-c","ls -lt $APPL_TOP/patch/115/odf/jtfgh.odf"};
    Also, you should read, digest and implement the recommendations of
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html .
    P.S Your urgency is not my problem and SHOUTING IS CONSIDERED VERY RUDE!

  • Can't connect to Exchange2003 Server through WRT54GS (via wireless)

    I'm having problems conencting to my MS Exchange 2003 server, from an Outlook 2003 Client, when using wireless on a WRT54GS.
    Hard wired - works fine.
    Wireless - connection times out ("unable to connect to exchange server")
    I can browse the internet through the wireless conenction, download (legal) music, etc. Cannot use Outlook/Exchange.
    I disabled the "firewall" features on the router. (block external requests, etc)
    WEP is enabled.
    The Router was bought about 6 months ago (original firmware)
    any suggestions? anyone successfully using Exchange across a wireless conenction?

    first i'd suggest that you upgrade to the latest firmware....also open ports 443-447 under the port forwarding section of the router.

  • How to write a file in unix server through oracle plsql code

    Hi All,
    My requirement is to create and write a file (any file for eg txt file) in unix box with in a specified directory through oracle plsql code.
    Oracle sits in windows server.
    using utl_file package we can create directory where oracle resides and write it there in oracle server in our case windows..
    But here we need to create,write a file but in unix server which is different server than where the oracle server resides..
    we are using Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production
    PL/SQL Release 11.2.0.2.0 - Production
    Can any one one please help me out in this issue...
    Thanks in Advance.
    Prakash

    Mr Prakash,
    Why are you asking this question multiple times in every forum you can spell?
    Valid responses have been presented to you already two times.
    Can you explain why you can't follow them up, but continue to abuse this forum by repeating doc questions?
    Sybrand Bakker
    Senior Oracle DBA

Maybe you are looking for

  • Broke my Photo Library

    Like other IPhoto users I've seen posting here, I found the "don't tamper with the library" prompt too late, after I mistakenly tried to trash photos in the Photo Library. Now I can't get the slideshow to work--the screen goes to black, nothing happe

  • Use OData/CSOM with Azure Application authentication

    Hello, I try to create an application which can access Project Online OData and is using Azure AD Application for authentication. So I started with the Research-Project-Code-Sample from the OfficeDev ( https://github.com/OfficeDev/Research-Project-Co

  • Transport table contents

    Hello experts I am trying to transport the contents of a table from one system to another, using a request. When I select all the table data in SE16 then and go to menu Table entry- Transport Entries. By default a prompt for customizing request pops

  • How to enable Dynamic Time Series?

    Hi expert, I tried to enabled Dynamic Time Series for an application, by go to Dimension Library, right click, select "Dynamic Time Series", then selected both YTD and QTD for generation 2 and 3 respectively, then refresh database. But found seems th

  • Connecting Mac OS X 10.5.4 with windows

    Hi, i am trying to connect the macbook to my pc directly through ethernet. i enebaled smb and followed things as given in other few articles still iam not able to connect to pc from Go-->connect to server. can any one guide me detaily? i am doing thi