Solved

Connect to UNIX - Sockets

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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Google Directions API to Map URL -C#? 3 46
Please explain the parts of these 2 LINQ expressions 3 81
Where is this file? 3 33
linq, c# 8 31
Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
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…
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…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…

740 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