Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在SSH连接成功后执行命令_Python_Linux_Ssh_Terminal_Raspberry Pi - Fatal编程技术网

Python 在SSH连接成功后执行命令

Python 在SSH连接成功后执行命令,python,linux,ssh,terminal,raspberry-pi,Python,Linux,Ssh,Terminal,Raspberry Pi,我想我可能在谷歌上搜索这些东西是错误的,但是我想知道我是否可以让我的raspberry Pi在我通过SSH连接到它之后执行一个命令 工作流程: 1) 通过终端将SSH转换为Pi 2) 登录后,Pi执行一个命令来显示当前温度(我已经知道这个命令) pi已经输出 Linux raspberrypi 3.10.25+ #622 PREEMPT Fri Jan 3 18:41:00 GMT 2014 armv6l The programs included with the Debian GNU/Li

我想我可能在谷歌上搜索这些东西是错误的,但是我想知道我是否可以让我的raspberry Pi在我通过SSH连接到它之后执行一个命令

工作流程: 1) 通过终端将SSH转换为Pi 2) 登录后,Pi执行一个命令来显示当前温度(我已经知道这个命令)

pi已经输出

Linux raspberrypi 3.10.25+ #622 PREEMPT Fri Jan 3 18:41:00 GMT 2014 armv6l

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Fri Jul 11 15:11:35 2014

我可能会误解这一点,甚至可能在上面的对话框中执行并显示了命令。

是的,这是可以做到的。我知道的方法利用了
子流程
。只要知道python脚本的名称和参数(如果有),就可以将它们传递到
子流程中。下面是一个如何通过python ssh脚本进行连接的示例(摘自):


只需将该命令附加到ssh命令

sshuser@server“回声测试”


“echo test”
在远程机器上执行。

您要查找的是motd,它在各种linux发行版上非常常见。这不是python中的(但可以)。motd在通过SSH登录时运行多个命令,并构造一条消息,输出给用户。有关这方面的更多信息(实际列出了温度)可在此处找到:。问题是,这可能会因linux发行版的不同而略有变化。在这里还可以找到一个好的git repo,它有一条很好的消息:

通过将命令放在shh命令之后,您可以从bash执行命令,而无需实际登录到另一台计算机:

$ ssh pi@pi_addr touch wat.txt
将创建文本文件~/wat.txt

这对于自动化来说有点麻烦,但是因为必须提供as密码,所以您可以在计算机上设置公共/私有RSA密钥,以便无需密码即可远程登录到pi。只需执行以下操作:

$ ssh-keygen -t rsa
    Generating public/private rsa key pair.
    Enter file in which to save the key (/home/a/.ssh/id_rsa):
    Created directory '/home/a/.ssh'.
    Enter passphase (empty for no passphrase):
    Enter the same passphrase again:
$ssh pi@pi_addr mkdir -p .ssh
$cat .ssh/id_rsa.pub | ssh pi@pi_addr 'cat >> .ssh/authorized_keys'
在运行ssh-keygen时,不要输入密码短语并保留所有默认值。现在,您将能够使用rn sshpi@pi_addr无需输入密码

python文件示例:

import subprocess

SERVER = "pi@pi_addr"
subprocess.call("ssh pi@pi_addr touch wat.txt")

它取决于shell的类型,但您可以向user.bashrc.profile(或shell使用的任何命令)添加命令。
import subprocess

SERVER = "pi@pi_addr"
subprocess.call("ssh pi@pi_addr touch wat.txt")