Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Connect to UNIX - Sockets

Posted on 2003-11-24
4
Medium Priority
?
422 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 2000 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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
In response to a need for security and privacy, and to continue fostering an environment members can turn to for support, solutions, and education, Experts Exchange has created anonymous question capabilities. This new feature is available to our Pr…
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…

660 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