NEWS

[C#] Hướng dẫn sử dụng Telnet để download và upload file

[C#] Hướng dẫn sử dụng Telnet để download và upload file
Đăng bởi: Thảo Meo - Lượt xem: 14430 08:00:39, 22/08/2017C#   In bài viết

Bài viết hôm nay, mình sẽ hướng dẫn các bạn sử dụng Telnet trong C# để download hoặc upload file lên máy telnet client.

C# Hướng dẫn sử dụng Telnet Client trong lập trình csharp

Nếu các bạn nào, đã từng làm việc với máy chấm công để download dữ liệu về. Thì thường là khi mua máy, nhà sản xuất sẽ cung cấp cho chúng ta một bộ SDK để lấy dữ liệu.

Thông qua các giao thức như: TCP/IP, COM port, USB.

Thường thì các máy chấm công hiện tại sẽ chạy hệ điều hành Boxy Linux. Các bạn có thể kết nối telnet trực tiếp đến máy chấm công, hay bất kỳ một máy client nào để lấy dữ liệu.

Dưới đây, là giao diện telnet máy chấm công RONALD JACK - K300 

telnet C#

- Đầu tiên các bạn tạo 1 class có tên TelnetConnection.cs với nội dung như sau:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Telnet
{
    enum Verbs
    {
        WILL = 251,
        WONT = 252,
        DO = 253,
        DONT = 254,
        IAC = 255
    }

    enum Options
    {
        SGA = 3
    }
    public class TelnetConnection
    {
        TcpClient tcpSocket;

        int TimeOutMs = 100;

        public TelnetConnection(string Hostname, int Port)
        {
            tcpSocket = new TcpClient(Hostname, Port);

        }

        public string Login(string Username, string Password, int LoginTimeOutMs)
        {
            int oldTimeOutMs = TimeOutMs;
            TimeOutMs = LoginTimeOutMs;
            string s = Read();
            if (!s.TrimEnd().EndsWith(":"))
                throw new Exception("Failed to connect : no login prompt");
            WriteLine(Username);

            s += Read();
            if (!s.TrimEnd().EndsWith(":"))
                throw new Exception("Failed to connect : no password prompt");
            WriteLine(Password);

            s += Read();
            TimeOutMs = oldTimeOutMs;
            return s;
        }

        public void WriteLine(string cmd)
        {
            Write(cmd + "
");
        }

        public void Write(string cmd)
        {
            if (!tcpSocket.Connected) return;
            byte[] buf = System.Text.ASCIIEncoding.ASCII.GetBytes(cmd.Replace("xFF", "xFFxFF"));
            tcpSocket.GetStream().Write(buf, 0, buf.Length);
        }

        public string Read()
        {
            if (!tcpSocket.Connected) return null;
            StringBuilder sb = new StringBuilder();
            do
            {
                ParseTelnet(sb);
                System.Threading.Thread.Sleep(TimeOutMs);
            } while (tcpSocket.Available > 0);
            return sb.ToString();
        }

        public bool IsConnected
        {
            get { return tcpSocket.Connected; }
        }

        void ParseTelnet(StringBuilder sb)
        {
            while (tcpSocket.Available > 0)
            {
                int input = tcpSocket.GetStream().ReadByte();
                switch (input)
                {
                    case -1:
                        break;
                    case (int)Verbs.IAC:
                        // interpret as command
                        int inputverb = tcpSocket.GetStream().ReadByte();
                        if (inputverb == -1) break;
                        switch (inputverb)
                        {
                            case (int)Verbs.IAC:
                                //literal IAC = 255 escaped, so append char 255 to string
                                sb.Append(inputverb);
                                break;
                            case (int)Verbs.DO:
                            case (int)Verbs.DONT:
                            case (int)Verbs.WILL:
                            case (int)Verbs.WONT:
                                // reply to all commands with "WONT", unless it is SGA (suppres go ahead)
                                int inputoption = tcpSocket.GetStream().ReadByte();
                                if (inputoption == -1) break;
                                tcpSocket.GetStream().WriteByte((byte)Verbs.IAC);
                                if (inputoption == (int)Options.SGA)
                                    tcpSocket.GetStream().WriteByte(inputverb == (int)Verbs.DO ? (byte)Verbs.WILL : (byte)Verbs.DO);
                                else
                                    tcpSocket.GetStream().WriteByte(inputverb == (int)Verbs.DO ? (byte)Verbs.WONT : (byte)Verbs.DONT);
                                tcpSocket.GetStream().WriteByte((byte)inputoption);
                                break;
                            default:
                                break;
                        }
                        break;
                    default:
                        sb.Append((char)input);
                        break;
                }
            }
        }
    }
}

- Tiếp đến, mình sẽ viết hàm linux như cd, ls để truy cập vào thư mục tập tin cần lấy, rồi các bạn tiếp tục sử dụng lệnh cat để đọc file và get dữ liệu đọc được từ console về.

- Nếu bạn nào muốn download file về máy chấm công thì các bạn sử dụng lệnh Wget:

vb: wget https://laptrinhvb.net/favicon.ico

Source code ghi file từ giao diện dòng lệnh:

Imports Telnet

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim tc As TelnetConnection = New TelnetConnection("192.168.0.145", 23)
        Dim s As String = tc.Login("root", "solokey", 100)
        MessageBox.Show(s)

        ' server output should end with "$" or ">", otherwise the connection failed
        Dim prompt As String = s.TrimEnd()
        prompt = s.Substring(prompt.Length - 1, 1)
        If prompt <> "$" AndAlso prompt <> "#" Then
            Throw New Exception("Connection failed")
        End If

        prompt = ""
        If tc.IsConnected Then
            tc.WriteLine("cd /mnt/mtdblock")
            tc.WriteLine("cat extlog.dat")
            System.IO.File.WriteAllText("extlog.dat", tc.Read())

        End If
    End Sub
End Class

HAVE FUN:)

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[C#] Hướng dẫn sử dụng Telnet để download và upload file
Đăng bởi: Thảo Meo - Lượt xem: 14430 08:00:39, 22/08/2017C#   In bài viết

CÁC BÀI CÙNG CHỦ ĐỀ

Đọc tiếp
.