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
相关推荐
IT_陈寒21 分钟前
React状态管理终极对决:Redux vs Context API谁更胜一筹?
前端·人工智能·后端
晨星shine1 小时前
GC、Dispose、Unmanaged Resource 和 Managed Resource
后端·c#
Kagol1 小时前
TinyVue 支持 Skills 啦!现在你可以让 AI 使用 TinyVue 组件搭建项目
前端·agent·ai编程
柳杉1 小时前
从零打造 AI 全球趋势监测大屏
前端·javascript·aigc
simple_lau1 小时前
Cursor配置MasterGo MCP:一键读取设计稿生成高还原度前端代码
前端·javascript·vue.js
睡不着先生1 小时前
如何设计一个真正可扩展的表单生成器?
前端·javascript·vue.js
天蓝色的鱼鱼2 小时前
模块化与组件化:90%的前端开发者都没搞懂的本质区别
前端·架构·代码规范
明君879972 小时前
Flutter 如何给图片添加多行文字水印
前端·flutter
进击的尘埃2 小时前
AI 代码审查工具链搭建:用 AST 解析 + LLM 实现自动化 Code Review 的前端工程方案
javascript
juejin_cn2 小时前
[转][译] 从零开始构建 OpenClaw — 第五部分(对话压缩)
javascript