2017-07-31 88 views
0

我在我的服务器中有一个shell脚本,我希望它能在树莓派中运行python脚本并将结果获取到我的服务器终端。如何远程运行python脚本并输出输出

要做到这一点,我试用了expect包。这是我的shell脚本。

#!/usr/bin/expect -f 

spawn ssh [email protected] 

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


sudo python [email protected] TemparatureSensor/Adafruit_Python_DHT/examples/AdafruitDHT.py 11 4 

由此,我可以访问树莓派,但不能执行python脚本。

我在这里错过了什么?如何使这个工作?

在此先感谢。

+0

你可以使用子模块,用来捕获一个命令的输出 – Kallz

回答

0

我写了这个模块封装了paramiko包,

见链接here

用法示例:

from ssh import ssh_connect 
server = ssh_connect("user", "password", "server address") 

@server 
def some_function(): 
    some_code 

some_function() 
+0

感谢您的快速回答,我看到了你的回购时,我GOOGLE了我的问题。但在这里我想要一个shell脚本答案。 – Sachith

0

你想围绕做它的其他方式。制作一个执行命令(或你的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]) 
相关问题