news 2026/6/23 19:34:44

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/6/23 20:26:27

hasattr()函数和getattr()函数

hasattr()函数 hasattr() 是 Python 的内置函数&#xff0c;用于检查对象是否具有指定名称的属性&#xff08;或方法&#xff09;。 语法&#xff1a; hasattr(object, name) 参数&#xff1a; object&#xff1a;要检查的对象。name&#xff1a;字符串&#xff0c;表示要检查的…

作者头像 李华
网站建设 2026/6/23 18:58:58

Windows系统清理优化神器!支持Win10/11磁盘空间注册表清理,开机自启动项管理、程序应用安装更新卸载,电脑性能优化设置增强!

下载&#xff1a;https://tool.nineya.com/s/1jbp5vf11 这可不是普通的清理软件&#xff0c;而是集清理、优化、加速于一体的全能型选手&#xff0c;能帮你把电脑收拾得明明白白&#xff0c;运行速度直接起飞&#xff01; 首先说说它的 “清理能力”。这软件能彻底卸载那些你不…

作者头像 李华
网站建设 2026/6/23 18:58:59

EmotiVoice语音合成日志记录规范:便于调试与审计

EmotiVoice语音合成日志记录规范&#xff1a;便于调试与审计 在当前AI驱动的语音交互场景中&#xff0c;用户早已不再满足于“能说话”的机器声音。从智能客服到虚拟主播&#xff0c;从有声读物到游戏NPC&#xff0c;人们期待的是富有情感、自然流畅、甚至具备个性辨识度的语音…

作者头像 李华
网站建设 2026/6/23 18:57:29

EmotiVoice语音合成多区域部署架构设计

EmotiVoice语音合成多区域部署架构设计 在今天的智能服务生态中&#xff0c;用户对语音交互的期待早已超越“能听清”这一基本要求。无论是虚拟偶像的一句带笑哽咽&#xff0c;还是客服机器人在安抚客户时流露出的温和语调&#xff0c;背后都离不开高表现力语音合成技术的进步。…

作者头像 李华
网站建设 2026/6/23 18:54:10

不常用但超实用!QSpinBox 九大隐藏技巧

今天和大家分享一些 Qt 中 QSpinBox 控件的高级功能。这些功能不仅能让你的应用界面更加灵活&#xff0c;还能提升用户体验&#xff0c;尤其是在处理数值输入和界面交互时。虽然 QSpinBox 是一个常见的控件&#xff0c;大家经常用它来处理整数的输入&#xff0c;但它其实还有很…

作者头像 李华