[Python] I am having trouble running a command on a remote host in Python

Discussão em 'Python' iniciado por Stack, Março 27, 2025.

  1. Stack

    Stack Membro Participativo

    I need to run a command on a remote host from a Python 3 script. I have tried several methods, but I cannot get any of them working. I tried using paramiko but pip fails when attempting to load the bcrypt module from the cryptography library. Apparently there is a missing equals sign according to the Python exception when running pip3 install paramiko.

    I tried using pxssh from pexpect, but it raises an exception when I try to login saying it cannot establish a connection to the host. It does this whether I try the remote host or localhost

    #! /usr/bin/python3

    from pexpect import pxssh
    ssh = pxssh.pxssh()

    if not ssh.login("192.168.1.34", "xxxxxxx", "yyyyyyyy"):
    print("Failed")



    I tried the following code:

    #! /usr/bin/python3

    import time, subprocess, sys

    IP = "192.168.1.34"

    with open ("/var/run/thermostat/insideT", "r") as infile:
    Temp = float(infile.read()) # Get inside temperature
    if Temp > 75:
    TString = IP + '"/usr/bin/gpio write 0 1"\n
    subprocess.run(["ssh", TString])


    But I get an error from ssh saying it cannot resolve the hostname 192.168.1.34. I have tried several different variations on the subprocess call.

    ssh 192.168.1.34 "gpio write 0 1" works just fine.

    Another way to handle this would be to read the value of the /var/run/thermostat/insideT on the local system from the remote system if that would be easier. I can run the script from either system.

    Both hosts are Raspberry Pi systems running a recent version of Raspberry Pi OS. Note I have a passwordless login enabled for ssh between the systems.

    Continue reading...

Compartilhe esta Página