Solved

Connect to UNIX - Sockets

Posted on 2003-11-24
4
413 Views
Last Modified: 2010-07-27
I have dozens of ID's and Passwords to UNIX servers that require a password change ever 60 days.  I want to create Windows Application to manage my UNIX passwords.  I'm willing to start small.  I need help issuing simple UNIX commands through TCP/IP.  Each of the UNIX boxes have a telnet listener on port 23.  I'd like to utilize this to initiate a conversation.

I have read the following links but need additional help:
1) http://www.experts-exchange.com/Programming/Programming_Languages/C_Sharp/Q_20384598.html?query=UNIX&searchType=topic
2) http://www.gotdotnet.com/community/usersamples/Default.aspx?query=telnet
3) http://groups.google.com/groups?q=C%23+connect+to+UNIX&hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=ccdac0da.0309062106.375c5cde%40posting.google.com&rnum=7
4) http://www.private.org.il/mini-tcpip.faq.html#3.%20Of%20the%20rexec%20protocol.


Below is the code I'm using to no avail.  I get a 3 funky characters returned.  A triangle,  } and $.  I must be doing something wrong.



using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Configuration;

namespace RemoteConsole
{
      /// <summary>
      /// RemoteConsoleClient
      /// </summary>
      class RemoteConsoleClient
      {
            TcpClient tcpClient;
            NetworkStream networkStream;
            
            private byte[] buffer = new byte[400];
            
            private AsyncCallback callBack;

            AutoResetEvent evtSessionEnd = new AutoResetEvent(false);
            StreamWriter streamWriter;

            public RemoteConsoleClient()
            {
                  //string Host = "localhost";
                  string Host = "serverDNS";
                  int HostPort = 23;

                  // Fetch Host from the configuration file
                  Host = ConfigurationSettings.AppSettings.Get("Host");
                  if (Host == null)
                        Host = "serverDNS";

                  // Fetch HostPort from the configuration file
                  try
                  {
                        HostPort = Int32.Parse(ConfigurationSettings.AppSettings.Get("HostPort"));
                  }
                  catch
                  {
                        // if no configuration file found - the port value will stay intact (default)
                  }
                  
                  // Connect to the RemoteConsole Server
                  tcpClient = new TcpClient();
                  
                  try
                  {
                        tcpClient.Connect(Host, HostPort);
                  }
                  catch
                  {
                        Console.WriteLine("Can't connect server " + Host + " on port " + HostPort.ToString());
                        tcpClient = null;
                        return;
                  }

                  // Tune the connection
                  tcpClient.ReceiveTimeout = 5;
                  tcpClient.SendTimeout = 5;
                  tcpClient.NoDelay = true;

                  // Get the network stream
                  networkStream = tcpClient.GetStream();

                  // initialize a callback waiting for the information from the stream
                  callBack = new AsyncCallback(OnCompletedRead);
                  networkStream.BeginRead(buffer, 0, buffer.Length, callBack, null);
                  streamWriter = new StreamWriter(networkStream);
                  streamWriter.AutoFlush = true;
            }

            /// <summary>
            /// Callback function, waiting for the information from the network stream
            /// </summary>
            void OnCompletedRead(IAsyncResult asyncResult)
            {
                  if (asyncResult == null)
                        Shutdown();

                  try
                  {
                        int bytesRead = networkStream.EndRead(asyncResult);

                        if (bytesRead > 0)
                        {
                              // Trnaslate the data to the string and dump it to the console
                              String str = Encoding.ASCII.GetString(buffer, 0, bytesRead);
                              Console.Write(str);
                  
                              // Reinitialize callback
                              networkStream.BeginRead(buffer, 0, buffer.Length, callBack, null);
                        }
                        else
                              // the connection was terminated by the server side
                              Shutdown();
                  }
                  catch
                  {
                        // the connection was terminated by the server side
                        Shutdown();
                  }
            }

            /// <summary>
            /// Main Console thread
            /// </summary>
            public void Run()
            {
                  // if there is no connection - even don't start the interaction with the user
                  if (tcpClient == null)
                  {
                        return;
                  }

                  Console.WriteLine("Type \"exit\" to close the remote session.\n");

                  // Receive the commands from the console and send them to the server.
                  string str;
                  do
                  {
                        str = Console.ReadLine();

                        if (tcpClient != null)
                              streamWriter.WriteLine(str);
                        else
                              break;
                  } while (str.ToLower() != "exit");

                  // Shutdown the network connection
                  Shutdown();
            }

            /// <summary>
            /// Shuts the connection down
            /// </summary>
            public void Shutdown()
            {
                  // Shutdown the network connection
                  if (tcpClient != null)
                  {
                        lock(tcpClient)
                        {
                              try
                              {
                                    streamWriter.Close();
                                    networkStream.Close();
                                    tcpClient.Close();
                              }
                              catch
                              {
                              }

                              Console.WriteLine("\nThe session was closed.");

                              tcpClient = null;
                        }
                  }
            }

            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main(string[] args)
            {
                  RemoteConsoleClient client = new RemoteConsoleClient();
                  client.Run();
            }
      }
}
0
Comment
Question by:jbauer22
  • 2
  • 2
4 Comments
 
LVL 18

Expert Comment

by:testn
ID: 9815580
connect to telnet requires some handshake.... use the library here....
http://www.c-sharpcorner.com/Code/2003/Jan/TelnetScripting.asp
0
 
LVL 2

Author Comment

by:jbauer22
ID: 9817833
testn,

Can you provide a code example on how to use this dll to connect to UNIX.
0
 
LVL 2

Author Comment

by:jbauer22
ID: 9821446
Please?  When I use the connect method it appears to return at box and }$.

Need help.
0
 
LVL 18

Accepted Solution

by:
testn earned 500 total points
ID: 9822272
It will work with OpenVMS only. To make it work with regular unix server, you have to incorporate the stuff from http://www.csharphelp.com/archives/archive239.html

Sorry that I don't have time to make it work.

0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Introduction                                                 Was the var keyword really only brought out to shorten your syntax? Or have the VB language guys got their way in C#? What type of variable is it? All will be revealed.   Also called…
We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now