Wireless sensor networks (WSNs) are characterized by high node density and finite energy storage. Each node exchanges information with all its neighboring nodes frequently, which makes it easy for nodes to run out of energy, leading to paralysis of the WSNs when facing network malicious code attacks. To address this problem, a malicious code propagation model based on sleep-monitoring technology for WSNs is proposed. As a Multi-compartment propagation, sleep nodes and monitoring nodes are introduced to the conventional SIR model. Sleep nodes can turn the infected node into a dormant state and stop the dissemination of information to save energy. Monitoring nodes can contain malicious codes spread in wireless sensor networks by sharing prevention information in real time. Additionally, by calculating the equilibrium point and propagation threshold of the new feedback model, the corresponding Lyapunov function is constructed to prove the local stability and global stability of the equilibrium point. Finally, the results of numerical simulation experiments show that when the sleep rate is 0.3 and feedback rate is 0.0000005, the number of infected nodes in the wireless sensor network decreases by 43.45%. Therefore, adding sleep-monitoring technology can effectively control the spread of malicious code in the networks.