Agriculture 4.0 is transforming modern farming practices. It uses Internet of Things devices, smart sensors, drones, automated irrigation systems, and cloud-based technologies. These new technologies help farmers improve operational efficiency and use resources wisely. However, they also make Agriculture 4.0 networks more vulnerable to cyberattacks. Various types of attacks can disrupt agricultural operations, such as Distributed Denial-of-Service attacks, Port Scanning, Botnet activities, and Brute Force intrusions. These attacks can disrupt farming operations and put important Agriculture 4.0 data at risk. Traditional intrusion detection methods mostly look for known threats and often miss new or unknown ones. This study proposes a Machine Learning-based Intrusion Detection System (IDS) for Agriculture 4.0 environments using the Random Forest algorithm. The Farm Flow dataset containing agricultural network traffic was utilized for training and evaluation. Data preprocessing techniques, including feature selection, label encoding, and normalization, were applied to improve model performance. The proposed system identifies whether network traffic is normal or associated with attacks such as DDoS, Port Scan, Botnet, or Brute Force. The system was evaluated using performance metrics such as accuracy and precision, along with a confusion matrix. The results show that using machine learning can effectively enhance the security of farming systems against cyberattacks by detecting malicious activities quickly and accurately. Furthermore, the proposed system provides a cost-effective approach for securing Agriculture 4.0 systems.