news 2026/4/18 23:48:01

C#实现的远程控制系统

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
C#实现的远程控制系统

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


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

usingSystem;usingSystem.Collections.Concurrent;usingSystem.Net;usingSystem.Net.Sockets;usingSystem.Security.Cryptography;usingSystem.Text;usingSystem.Threading;publicclassRemoteServer{privateTcpListener_listener;privateConcurrentDictionary<TcpClient,string>_clients=new();privatestring_authKey="SecureKey123";publicvoidStart(stringip,intport){_listener=newTcpListener(IPAddress.Parse(ip),port);_listener.Start();Console.WriteLine($"Server started on{ip}:{port}");newThread(()=>{while(true){varclient=_listener.AcceptTcpClient();_=newThread(()=>HandleClient(client)).Start();}}).Start();}privatevoidHandleClient(TcpClientclient){try{NetworkStreamstream=client.GetStream();byte[]authBuffer=newbyte[1024];intbytesRead=stream.Read(authBuffer,0,authBuffer.Length);stringauthData=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;stringcommand=Encoding.UTF8.GetString(authBuffer,0,bytesRead).Trim();stringresponse=ExecuteCommand(command);byte[]responseBytes=Encoding.UTF8.GetBytes(response);stream.Write(responseBytes,0,responseBytes.Length);}}catch(Exceptionex){Console.WriteLine($"Error:{ex.Message}");}finally{_clients.TryRemove(client,out_);client.Close();}}privateboolVerifyAuth(stringauthData){string[]parts=authData.Split('|');if(parts.Length!=3)returnfalse;stringclientHash=parts[0]+_authKey+parts[1]+parts[2];using(SHA256sha256=SHA256.Create()){byte[]hashBytes=sha256.ComputeHash(Encoding.UTF8.GetBytes(clientHash));stringserverHash=BitConverter.ToString(hashBytes).Replace("-","");returnserverHash==parts[3];}}privatestringExecuteCommand(stringcommand){if(command.ToLower()=="exit")return"Goodbye!";if(command.ToLower()=="gettime")returnDateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");try{Processprocess=newProcess();process.StartInfo.FileName="cmd.exe";process.StartInfo.Arguments=$"/C{command}";process.StartInfo.RedirectStandardOutput=true;process.StartInfo.UseShellExecute=false;process.Start();stringoutput=process.StandardOutput.ReadToEnd();process.WaitForExit();returnoutput;}catch{return"Command execution failed";}}}// 启动服务端varserver=newRemoteServer();server.Start("0.0.0.0",8888);

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

usingSystem;usingSystem.Net.Sockets;usingSystem.Security.Cryptography;usingSystem.Text;usingSystem.Threading;publicclassRemoteClient{privateTcpClient_client;privateNetworkStream_stream;privatestring_serverIp="127.0.0.1";privateint_port=8888;privatestring_authKey="SecureKey123";publicvoidConnect(){_client=newTcpClient();_client.Connect(_serverIp,_port);_stream=_client.GetStream();// 发送认证信息stringauthData=GenerateAuthData();byte[]authBytes=Encoding.UTF8.GetBytes(authData);_stream.Write(authBytes,0,authBytes.Length);newThread(ReceiveMessages).Start();}privatestringGenerateAuthData(){stringclientId=Guid.NewGuid().ToString();stringtimestamp=DateTime.Now.Ticks.ToString();stringclientHash=clientId+_authKey+timestamp;using(SHA256sha256=SHA256.Create()){byte[]hashBytes=sha256.ComputeHash(Encoding.UTF8.GetBytes(clientHash));stringserverHash=BitConverter.ToString(hashBytes).Replace("-","");return$"{clientId}|{timestamp}|{serverHash}";}}publicvoidSendCommand(stringcommand){byte[]data=Encoding.UTF8.GetBytes(command);_stream.Write(data,0,data.Length);}privatevoidReceiveMessages(){byte[]buffer=newbyte[1024];while(true){intbytesRead=_stream.Read(buffer,0,buffer.Length);if(bytesRead==0)break;stringresponse=Encoding.UTF8.GetString(buffer,0,bytesRead);Console.WriteLine("Response: "+response);}}}// 使用示例varclient=newRemoteClient();client.Connect();client.SendCommand("gettime");Thread.Sleep(1000);client.SendCommand("exit");

三、核心功能说明

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

四、扩展功能实现

1. 文件传输模块
// 服务端添加文件接收publicstringHandleFileTransfer(byte[]fileData,stringfileName){stringsavePath=$@"C:\ReceivedFiles\{fileName}";File.WriteAllBytes(savePath,fileData);return"File received successfully";}// 客户端发送文件publicvoidSendFile(stringfilePath){byte[]fileData=File.ReadAllBytes(filePath);stringfileName=Path.GetFileName(filePath);_stream.Write(Encoding.UTF8.GetBytes($"FILE|{fileName}"),0,1024);_stream.Write(fileData,0,fileData.Length);}
2. 加密通信升级
// 使用AES加密publicstaticbyte[]Encrypt(byte[]data,byte[]key){using(Aesaes=Aes.Create()){aes.Key=key;aes.GenerateIV();using(CryptoStreamcs=newCryptoStream(newMemoryStream(),aes.CreateEncryptor(),CryptoStreamMode.Write)){cs.Write(data,0,data.Length);cs.FlushFinalBlock();}returnaes.IV.Concat(aes.Key).ToArray();}}// 在客户端和服务端添加加密层

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

五、安全增强方案

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

  2. 命令白名单

    privatereadonlystring[]_allowedCommands={"gettime","systeminfo","tasklist"};if(!_allowedCommands.Contains(command.ToLower()))return"Command not allowed";
  3. 流量监控

    publicclassTrafficMonitor{privatelong_totalBytesSent=0;privatelong_totalBytesReceived=0;publicvoidUpdateSent(longbytes)=>Interlocked.Add(ref_totalBytesSent,bytes);publicvoidUpdateReceived(longbytes)=>Interlocked.Add(ref_totalBytesReceived,bytes);}

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

  • 添加图形化界面(WPF/WinForm)
  • 实现屏幕监控功能
  • 集成语音通讯模块
  • 开发移动端控制App
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/4/19 12:25:07

如何快速安装StrmAssistant插件:Emby媒体服务器终极增强指南

如何快速安装StrmAssistant插件&#xff1a;Emby媒体服务器终极增强指南 【免费下载链接】StrmAssistant Strm Assistant for Emby 项目地址: https://gitcode.com/gh_mirrors/st/StrmAssistant StrmAssistant是一款专为Emby媒体服务器设计的强大插件&#xff0c;能够显…

作者头像 李华
网站建设 2026/4/16 21:16:17

Doris集群搭建

Doris集群搭建 1、简介 搭建三节点存算一体Doris集群 FE、BE混合部署 版本号2.1.9 节点ip作用node310.1.0.21FE,BEnode410.1.0.18FE,BEnode410.1.0.19FE,BE 2、配置 配置每个节点Ip和Java环境 2.1、FE # Licensed to the Apache Software Foundation (ASF) under one …

作者头像 李华
网站建设 2026/4/15 19:07:51

8个AI论文工具,MBA轻松搞定毕业论文!

8个AI论文工具&#xff0c;MBA轻松搞定毕业论文&#xff01; AI 工具如何助力论文写作&#xff1f; 在当今信息爆炸的时代&#xff0c;MBA 学员们面对毕业论文的压力愈发显著。无论是选题、文献综述&#xff0c;还是数据整理与分析&#xff0c;每一个环节都可能成为难以逾越的障…

作者头像 李华
网站建设 2026/4/16 7:45:20

Android智能代理评估新范式:动态基准环境如何重塑移动AI测试标准

Android智能代理评估新范式&#xff1a;动态基准环境如何重塑移动AI测试标准 【免费下载链接】androidgen-glm-4-9b 项目地址: https://ai.gitcode.com/zai-org/androidgen-glm-4-9b 在移动AI技术快速迭代的当下&#xff0c;传统评估方法正面临严峻挑战。如何准确衡量A…

作者头像 李华
网站建设 2026/4/16 20:35:37

React Native Vision Camera实战:从零构建高性能AR拍摄应用

React Native Vision Camera实战&#xff1a;从零构建高性能AR拍摄应用 【免费下载链接】react-native-vision-camera &#x1f4f8; A powerful, high-performance React Native Camera library. 项目地址: https://gitcode.com/GitHub_Trending/re/react-native-vision-cam…

作者头像 李华
网站建设 2026/4/16 13:37:29

告别机械音!EmotiVoice让AI语音充满喜怒哀乐的真实情感

告别机械音&#xff01;EmotiVoice让AI语音充满喜怒哀乐的真实情感 在虚拟主播的直播间里&#xff0c;一个观众突然提问&#xff1a;“你真的开心吗&#xff1f;” 主播笑了——不是预录的那种生硬笑声&#xff0c;而是带着轻微颤抖、尾音上扬的、仿佛从心底涌出的真实喜悦。 这…

作者头像 李华