malware – Securing a new machine with a compromised network

I have a machine on my network that has been compromised many times and I'm trying to understand how that goes. After the machine was compromised for the last time, I turned off all parts of the computer, with the exception of the SATA DVD drive and the SD card reader. I then configured a new installation of Ubuntu 18 on the machine, connected to the machine and proceeded to update the computer with a compromised network. I assumed it was not a problem because the machine was already connected. However, my machine was compromised again shortly after, and I try to understand how.

This could be one of the following possibilities:

1) The DVD player or SD card reader was infected with malware infecting the new hard drive, which allowed access to the machine after it was connected to the network.

2) It was compromised by a vulnerability of the operating system before the update of the machine, because the attacker had already access to the network since the moment I connected the machine, before same as I can secure it.

What are the possibilities in these two scenarios?