Solved

Connect to UNIX - Sockets

Posted on 2003-11-24
4
414 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This is used to tweak the memory usage for your computer, it is used for servers more so than workstations but just be careful editing registry settings as it may cause irreversible results. I hold no responsibility for anything you do to the regist…
In this video I am going to show you how to back up and restore Office 365 mailboxes using CodeTwo Backup for Office 365. Learn more about the tool used in this video here: http://www.codetwo.com/backup-for-office-365/ (http://www.codetwo.com/ba…

910 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

22 Experts available now in Live!

Get 1:1 Help Now