Solved

Connect to UNIX - Sockets

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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

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

Suggested Solutions

Introduction Although it is an old technology, serial ports are still being used by many hardware manufacturers. If you develop applications in C#, Microsoft .NET framework has SerialPort class to communicate with the serial ports.  I needed to…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

822 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