成功SSH连接后执行命令
我觉得我可能在网上搜索这些内容时搞错了,不过我想知道能不能让我的树莓派在我通过SSH连接后自动执行一个命令。
操作流程:
- 通过终端SSH连接到树莓派
- 登录后,树莓派执行一个命令来显示当前的温度(我已经知道这个命令了)
树莓派已经输出了:
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
我可能完全误解了这一切,也许可以让这个命令在上面的对话框中执行并显示出来。
4 个回答
0
你可以在bash中执行一个命令,而不需要真正登录到另一台电脑,只需把命令放在ssh命令后面:
$ ssh pi@pi_addr touch wat.txt
这会创建一个文本文件 ~/wat.txt。
不过,这样做对于自动化来说有点麻烦,因为你需要输入密码。为了能够远程登录到你的树莓派而不需要输入密码,你可以在你的电脑上设置一个公钥/私钥的RSA密钥。具体步骤如下:
$ 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时,不要输入密码短语,保持所有默认设置。这样,你就可以直接用ssh pi@pi_addr登录,而不需要输入密码了。
下面是一个示例的python文件:
import subprocess
SERVER = "pi@pi_addr"
subprocess.call("ssh pi@pi_addr touch wat.txt")
0
只需要把命令加到ssh命令后面就可以了。
ssh user@server "echo test"
"echo test"
这个命令会在远程机器上执行。
0
没错,这个是可以做到的。我知道的一种方法是使用 subprocess
这个模块,详细信息可以查看这里:https://docs.python.org/2/library/subprocess.html。只要你知道要运行的 Python 脚本的名字和参数(如果有的话),就可以把它们传递给 subprocess
。下面是一个通过 Python 脚本连接 SSH 的例子(摘自 http://python-for-system-administrators.readthedocs.org/en/latest/ssh.html):
import subprocess
import sys
HOST="www.example.org"
# Ports are handled in ~/.ssh/config since we use OpenSSH
COMMAND="uname -a"
ssh = subprocess.Popen(["ssh", "%s" % HOST, COMMAND],
shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
result = ssh.stdout.readlines()
if result == []:
error = ssh.stderr.readlines()
print >>sys.stderr, "ERROR: %s" % error
else:
print result