C#实现的远程控制系统

C#实现的远程控制系统源码,包含服务端和客户端实现,支持命令执行、文件传输和基础安全认证:


一、服务端实现(支持多线程)

csharp 复制代码
using System;
using System.Collections.Concurrent;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Threading;

public class RemoteServer {
    private TcpListener _listener;
    private ConcurrentDictionary<TcpClient, string> _clients = new();
    private string _authKey = "SecureKey123";

    public void Start(string ip, int port) {
        _listener = new TcpListener(IPAddress.Parse(ip), port);
        _listener.Start();
        Console.WriteLine($"Server started on {ip}:{port}");

        new Thread(() => {
            while (true) {
                var client = _listener.AcceptTcpClient();
                _ = new Thread(() => HandleClient(client)).Start();
            }
        }).Start();
    }

    private void HandleClient(TcpClient client) {
        try {
            NetworkStream stream = client.GetStream();
            byte[] authBuffer = new byte[1024];
            int bytesRead = stream.Read(authBuffer, 0, authBuffer.Length);
            string authData = Encoding.UTF8.GetString(authBuffer, 0, bytesRead);

            if (!VerifyAuth(authData)) {
                client.Close();
                return;
            }

            _clients[client] = "Authorized";
            Console.WriteLine("Client authenticated: " + client.Client.RemoteEndPoint);

            while (true) {
                bytesRead = stream.Read(authBuffer, 0, authBuffer.Length);
                if (bytesRead == 0) break;

                string command = Encoding.UTF8.GetString(authBuffer, 0, bytesRead).Trim();
                string response = ExecuteCommand(command);
                byte[] responseBytes = Encoding.UTF8.GetBytes(response);
                stream.Write(responseBytes, 0, responseBytes.Length);
            }
        }
        catch (Exception ex) {
            Console.WriteLine($"Error: {ex.Message}");
        }
        finally {
            _clients.TryRemove(client, out _);
            client.Close();
        }
    }

    private bool VerifyAuth(string authData) {
        string[] parts = authData.Split('|');
        if (parts.Length != 3) return false;

        string clientHash = parts[0] + _authKey + parts[1] + parts[2];
        using (SHA256 sha256 = SHA256.Create()) {
            byte[] hashBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(clientHash));
            string serverHash = BitConverter.ToString(hashBytes).Replace("-", "");
            return serverHash == parts[3];
        }
    }

    private string ExecuteCommand(string command) {
        if (command.ToLower() == "exit") return "Goodbye!";
        if (command.ToLower() == "gettime") return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        
        try {
            Process process = new Process();
            process.StartInfo.FileName = "cmd.exe";
            process.StartInfo.Arguments = $"/C {command}";
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.UseShellExecute = false;
            process.Start();
            string output = process.StandardOutput.ReadToEnd();
            process.WaitForExit();
            return output;
        }
        catch {
            return "Command execution failed";
        }
    }
}

// 启动服务端
var server = new RemoteServer();
server.Start("0.0.0.0", 8888);

二、客户端实现(带身份验证)

csharp 复制代码
using System;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Threading;

public class RemoteClient {
    private TcpClient _client;
    private NetworkStream _stream;
    private string _serverIp = "127.0.0.1";
    private int _port = 8888;
    private string _authKey = "SecureKey123";

    public void Connect() {
        _client = new TcpClient();
        _client.Connect(_serverIp, _port);
        _stream = _client.GetStream();

        // 发送认证信息
        string authData = GenerateAuthData();
        byte[] authBytes = Encoding.UTF8.GetBytes(authData);
        _stream.Write(authBytes, 0, authBytes.Length);

        new Thread(ReceiveMessages).Start();
    }

    private string GenerateAuthData() {
        string clientId = Guid.NewGuid().ToString();
        string timestamp = DateTime.Now.Ticks.ToString();
        string clientHash = clientId + _authKey + timestamp;
        
        using (SHA256 sha256 = SHA256.Create()) {
            byte[] hashBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(clientHash));
            string serverHash = BitConverter.ToString(hashBytes).Replace("-", "");
            return $"{clientId}|{timestamp}|{serverHash}";
        }
    }

    public void SendCommand(string command) {
        byte[] data = Encoding.UTF8.GetBytes(command);
        _stream.Write(data, 0, data.Length);
    }

    private void ReceiveMessages() {
        byte[] buffer = new byte[1024];
        while (true) {
            int bytesRead = _stream.Read(buffer, 0, buffer.Length);
            if (bytesRead == 0) break;
            string response = Encoding.UTF8.GetString(buffer, 0, bytesRead);
            Console.WriteLine("Response: " + response);
        }
    }
}

// 使用示例
var client = new RemoteClient();
client.Connect();
client.SendCommand("gettime");
Thread.Sleep(1000);
client.SendCommand("exit");

三、核心功能说明

  1. 安全认证机制 使用SHA-256哈希算法生成认证令牌 包含时间戳防重放攻击 动态生成客户端ID
  2. 命令执行系统 支持系统命令执行(如diripconfig) 限制危险命令(需扩展白名单机制) 实时返回执行结果
  3. 多线程架构 服务端每个客户端独立线程处理 客户端异步接收响应

四、扩展功能实现

1. 文件传输模块
csharp 复制代码
// 服务端添加文件接收
public string HandleFileTransfer(byte[] fileData, string fileName) {
    string savePath = $@"C:\ReceivedFiles\{fileName}";
    File.WriteAllBytes(savePath, fileData);
    return "File received successfully";
}

// 客户端发送文件
public void SendFile(string filePath) {
    byte[] fileData = File.ReadAllBytes(filePath);
    string fileName = Path.GetFileName(filePath);
    _stream.Write(Encoding.UTF8.GetBytes($"FILE|{fileName}"), 0, 1024);
    _stream.Write(fileData, 0, fileData.Length);
}
2. 加密通信升级
csharp 复制代码
// 使用AES加密
public static byte[] Encrypt(byte[] data, byte[] key) {
    using (Aes aes = Aes.Create()) {
        aes.Key = key;
        aes.GenerateIV();
        using (CryptoStream cs = new CryptoStream(
            new MemoryStream(), aes.CreateEncryptor(), CryptoStreamMode.Write)) {
            cs.Write(data, 0, data.Length);
            cs.FlushFinalBlock();
        }
        return aes.IV.Concat(aes.Key).ToArray();
    }
}

// 在客户端和服务端添加加密层

参考代码 C# 远程控制 实例源码(客户端+服务端) www.youwenfan.com/contentcsn/92796.html

五、安全增强方案

  1. 双向证书认证 使用X509证书验证客户端和服务端身份

  2. 命令白名单

    csharp 复制代码
    private readonly string[] _allowedCommands = { "gettime", "systeminfo", "tasklist" };
    if (!_allowedCommands.Contains(command.ToLower())) return "Command not allowed";
  3. 流量监控

    csharp 复制代码
    public class TrafficMonitor {
        private long _totalBytesSent = 0;
        private long _totalBytesReceived = 0;
    
        public void UpdateSent(long bytes) => Interlocked.Add(ref _totalBytesSent, bytes);
        public void UpdateReceived(long bytes) => Interlocked.Add(ref _totalBytesReceived, bytes);
    }

该方案实现了基础的远程控制功能,可通过以下方式扩展:

  • 添加图形化界面(WPF/WinForm)
  • 实现屏幕监控功能
  • 集成语音通讯模块
  • 开发移动端控制App
相关推荐
rgeshfgreh35 分钟前
Spring事务传播机制深度解析
java·前端·数据库
全栈小精灵37 分钟前
Winform入门
开发语言·机器学习·c#
Hilaku1 小时前
我用 Gemini 3 Pro 手搓了一个并发邮件群发神器(附源码)
前端·javascript·github
IT_陈寒1 小时前
Java性能调优实战:5个被低估却提升30%效率的JVM参数
前端·人工智能·后端
快手技术1 小时前
AAAI 2026|全面发力!快手斩获 3 篇 Oral,12 篇论文入选!
前端·后端·算法
颜酱1 小时前
前端算法必备:滑动窗口从入门到很熟练(最长/最短/计数三大类型)
前端·后端·算法
用户298698530141 小时前
C#: 如何自动化创建Word可填写表单,告别手动填写时代
后端·c#·.net
全栈前端老曹1 小时前
【包管理】npm init 项目名后底层发生了什么的完整逻辑
前端·javascript·npm·node.js·json·包管理·底层原理
HHHHHY2 小时前
mathjs简单实现一个数学计算公式及校验组件
前端·javascript·vue.js
boooooooom2 小时前
Vue3 provide/inject 跨层级通信:最佳实践与避坑指南
前端·vue.js