如何远程运行python脚本并控制输出

2024-04-27 00:43:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我的服务器中有一个shell脚本,我希望它用raspberry pi运行python脚本,并将结果发送到服务器的终端。你知道吗

为此,我尝试了expect包。这是我的shell脚本。你知道吗

#!/usr/bin/expect -f

spawn ssh pi@192.168.123.123

expect "password:"
send "pass\r"
interact


sudo python pi@192.168.123.123 TemparatureSensor/Adafruit_Python_DHT/examples/AdafruitDHT.py 11 4

由此,我可以访问raspberry pi,但不能执行python脚本。你知道吗

我错过了什么?如何让它发挥作用?你知道吗

提前谢谢。你知道吗


Tags: 服务器脚本send终端binusrpipass
1条回答
网友
1楼 · 发布于 2024-04-27 00:43:37

你想反过来做。制作一个执行命令的python脚本(或者您可以使用python脚本)并将输出写入终端。你知道吗

下面是这样一个python脚本的例子,在我的例子中,它执行一个命令,调整我笔记本电脑的声音。你知道吗

#!/usr/bin/python
import paramiko
import sys

def sshConnect():
    HOST = "ip"
    USER = "user"
    KEYF = "/home/pi/.ssh/id_rsa"
    ssh = paramiko.SSHClient()
    key = paramiko.RSAKey.from_private_key_file(KEYF)
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    print "[*] Connecting..."
    ssh.connect(hostname=HOST, username=USER, pkey=key)
    print "[+] Connected!"
    return ssh

def setVolume(ssh, volume):
    command = 'osascript -e "set Volume %s" ' % (volume)
    print "Executing %s" % (command)
    stdin,stdout,stderr = ssh.exec_command(command)
    print stdout.read() #this prints the result in the terminal
    errors = stderr.read() 
    if errors:
        print errors
    ssh.close()
    print "[+] Disconnected"

def main(volume):
    setVolume(sshConnect(), volume)

if __name__ == "__main__":
    main(sys.argv[1])

相关问题 更多 >