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");
三、核心功能说明
- 安全认证机制 使用SHA-256哈希算法生成认证令牌 包含时间戳防重放攻击 动态生成客户端ID
- 命令执行系统 支持系统命令执行(如
dir、ipconfig) 限制危险命令(需扩展白名单机制) 实时返回执行结果 - 多线程架构 服务端每个客户端独立线程处理 客户端异步接收响应
四、扩展功能实现
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
五、安全增强方案
-
双向证书认证 使用X509证书验证客户端和服务端身份
-
命令白名单
csharpprivate readonly string[] _allowedCommands = { "gettime", "systeminfo", "tasklist" }; if (!_allowedCommands.Contains(command.ToLower())) return "Command not allowed"; -
流量监控
csharppublic 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