if you activate telnet on your raspberry pi you can use this:
and use this instead in the python script
#!/usr/bin/python3
import telnetlib
import time
HOST = "192.168.1.165"
telnet = telnetlib.Telnet(HOST)
telnet.read_until(b":",3)
telnet.write(b"pi\n")
telnet.read_until(b":",3)
telnet.write(b"raspberry\n")
telnet.read_until(b"pi@raspberrypi:",10)
telnet.write(b"sudo shutdown -h now\n")
telnet.read_until(b"pi@raspberrypi:",10)
telnet.write(b"exit\n")
telnet.close()
im using Home Assistant Supervised, so im not sure if/how its working on other installations but its worth a try, good luck