通过SSH与树莓派通信

时间:2019-04-02 04:06:50

标签: python-3.x raspberry-pi3

我想在Android设备上使用SSH与树莓派3对话。如何让我的python脚本侦听通过SSH发送的命令?

我曾经能够在Arduino上做到这一点,并且想在我的PI上做到同样的事情?

1 个答案:

答案 0 :(得分:0)

好吧,所以无数小时之后,我都在浏览Python代码和一堆反复试验。我终于找到了对我有用的东西。这是我在树莓派上用来读取终端的代码:

import termios, fcntl, sys, os
fd = sys.stdin.fileno()

oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)

oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)

try:
    while 1:
        try:
            c = sys.stdin.read(1)
            print "Got character", repr(c)
        except IOError: pass
finally:
    termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
    fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)

因此,我使用python3 myscript.py从终端启动python代码,而我输入的内容都被捕获了。

像魅力一样工作。希望我可以帮助其他人。

忘记将链接添加到我找到的答案中:What's the simplest way of detecting keyboard input in python from the terminal?