2017-10-17 13 views
0

Bonjour à tous, je fais une voiture en Raspberry Pi-3. et j'envoie quelques commandes shh. mon problème id que je ne veux pas envoyer des commandes shh directement, bien que je veux envoyer une sortie d'une sortie de la console python comment puis-je faire?Je veux envoyer une sortie de script python à un shell SSH

+0

votre question n'est pas clair, voulez-vous envoyer la sortie (états d'impression, etc.) à un shell ssh ou avez-vous voulez-vous que la sortie de votre script python soit traitée comme des commandes shell? si le premier quel est le problème avec l'appel du script de la session ssh? –

+0

Je veux traiter la sortie de la console python comme entrée pour l'entrée du shell SSH – salmanarshad1999

+0

vraiment vous avez deux options, vous pouvez étendre votre connexion ssh en utilisant subprocess.Popen et envoyer des messages à cela, ou vous pouvez utiliser une bibliothèque python ssh comme http://www.paramiko.org/ de toute façon, vous devrez changer votre script de sorte que la "sortie" n'est pas imprimée, mais plutôt envoyé au sous-processus ou le module ssh –

Répondre

0

Vous pouvez utiliser la bibliothèque du système d'exploitation en python, ce qui permettra au programme python de s'intégrer au shell Unix.

#Import Library 
import os 

#Set the action to 0 as it's not needed right now 
action = 0 

#Loop infinitely 
while True: 
    #First of all, list the available actions and let the user choose one. 
    print('Actions that can be performed') 
    print('ID. Action') 
    print('') 
    print('1. Go Forward') 
    print('2. Go Backwards') 
    print('3. Stop') 
    print('') 
    print('0. Stop and exit program') 
    print('') 

    #Ask the 'driver' what they want the car to do. Program will hang continuing 
    #to perform any current action that was previously selected until a different 
    #action is provided. 
    action = int(input('Enter the numerical ID of the action and press return: ')) 

    #Do the action based on the numerical ID 
    if(action == 1): 
     os.system('shell-command-to-go-forward') 

    if(action == 2): 
     os.system('shell-command-to-go-backward') 

    if(action == 3): 
     os.system('shell-command-to-stop-everything') 

    if(action == 0): 
     os.system('shell-command-to-stop-everything') 
     exit(0) 

Si ce n'est pas ce que vous cherchez à faire, s'il vous plaît pourriez-vous être plus précis. Le script python devrait-il prendre n'importe quelle forme d'entrée de l'utilisateur ou pas?

0

Je ne peux pas vous aider avec la fonctionnalité ssh que vous cherchez, je n'ai jamais essayé cela et je n'ai pas les outils à ma disposition maintenant pour essayer. Cependant, je ne crois pas que ce soit le bon outil pour le but. à la place, je joins un exemple de serveur de socket avec une interface graphique tkinter, en appuyant sur les touches fléchées envoyer des événements au serveur socket, qui peut ensuite être traitée.

server.py:

import socket 

# Create a TCP/IP socket 
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 

# Bind the socket to the port 
server_address = ('localhost', 10000) 
print('starting up on %s port %s' % server_address) 
sock.bind(server_address) 

while True: 
    try: 
     # Listen for incoming connections 
     sock.listen(1) 

     while True: 
      # Wait for a connection 
      print('waiting for a connection') 
      connection, client_address = sock.accept() 

      try: 
       print('connection from', client_address) 

       # Receive the data in small chunks and retransmit it 
       while True: 
        data = connection.recv(16) 
        if data: 
         print('received "%s"' % data) 
         # here you can test the character received and act accordingly 
         # you could also opt to send data back the other way 
#      print('sending data back to the client') 
#      connection.sendall(data) 
        else: 
         print('no more data from', client_address) 
         break 

      finally: 
       # Clean up the connection 
       connection.close() 
    except: 
     pass 

client.py

import socket 
import tkinter as tk 

class App(tk.Tk): 
    def __init__(self): 
     tk.Tk.__init__(self) 
     self.title("Car control") 

     self.sock = None 

     self.addr = tk.Entry(self) 
     self.addr.insert(0, "127.0.0.1") 
     self.addr.grid(column=1, row=1, sticky="nesw") 

     self.button = tk.Button(self, text="Connect", command=self.connect) 
     self.button.grid(column=2, row=1, sticky="nesw") 

     self.bind("<KeyPress>", self.handle_binding) 
     self.bind("<KeyRelease>", self.handle_binding) 

    def connect(self): 
     try: 
      self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
      self.sock.connect((self.addr.get(),10000)) 
      self.addr.configure(state="disabled") 
      self.button.configure(text="Disconnect", command=self.disconnect) 
      self.focus() 
     except (ConnectionRefusedError, socket.gaierror): 
      pass 

    def disconnect(self): 
     self.sock.close() 
     self.sock = None 
     self.addr.configure(state="normal") 
     self.button.configure(text="Connect", command=self.connect) 

    def send(self, data): 
     if self.sock: 
      self.sock.sendall(data.encode('utf8')) 

    def handle_binding(self, event): 
     if event.widget != self.addr: # ignore key events aimed at texkbox 
      char = "" 
      if event.keysym == "Up": 
       char = "u" 
      elif event.keysym == "Down": 
       char = "d" 
      elif event.keysym == "Left": 
       char = "l" 
      elif event.keysym == "Right": 
       char = "r" 
      if event.type == '2': # pressed 
       self.send(char) 
      elif event.type == '3': # released 
       self.send(char.upper()) 

if __name__ == "__main__": 
    app = App() 
    app.mainloop()