RestConsole/de

From OpenSimulator

(Difference between revisions)
Jump to: navigation, search
Line 53: Line 53:
 
Rückgabe: (XML) <ConsoleSession><Result></Result></ConsoleSession><br />
 
Rückgabe: (XML) <ConsoleSession><Result></Result></ConsoleSession><br />
 
Die Sitzung ist geschlossen, und Sie müssen sich erneut anmelden, wenn Sie wollen, erneut einen Befehl zu senden.
 
Die Sitzung ist geschlossen, und Sie müssen sich erneut anmelden, wenn Sie wollen, erneut einen Befehl zu senden.
 +
= Clients =
  
== Beispiele ==
+
== C# ==
  
=== Python ===
+
A C# client is included with the Opensimulator distribution. It is rudimentary and not updated to the latest protocol versions.
<source lang="python">
+
 
#!/usr/bin/python
+
== Qt ==
  # This piece of code is published by thomax (txOh) (c) 2010 under the
+
 
  # Artistic License 1.0 (http://www.perlfoundation.org/artistic_license_1_0)
+
The Qt 5 based client is at https://github.com/MelanieT/OpenSimConsoleClient
   
+
 
  import urllib, urllib2
+
=== Binaries ===
  import xml.dom.minidom
+
Windows: http://opensimulator.org/downloads/ConsoleClient.zip
+
Mac: http://opensimulator.org/downloads/ConsoleClient.dmg
class UserConsoleClient():
+
Linux: TBD
+
 
    def __init__(self, addr):
+
= Beispiele =
        self.addr = addr
+
 
        url = self.addr + 'StartSession/'
+
== HINWEIS ==
+
 
        params = urllib.urlencode({
+
Some of the examples below are for an older version of the interface. They may work to a degree but need to be revised.
             'USER': 'Test',         # REST username
+
 
             'PASS': 'secret'       # REST password
+
=== node.js ===
         })
+
 
         data = urllib2.urlopen(url, params).read()
+
<source lang="javascript">
+
/*
        dom = xml.dom.minidom.parseString(data)
+
  | This piece of code is published by thomax (tx0h) (c) 2018 under the
         elem =  dom.getElementsByTagName('SessionID')
+
  | Artistic License 1.0 (http://www.perlfoundation.org/artistic_license_1_0)
        self.sessionid = elem[0].childNodes[0].nodeValue
+
  |
+
  | I removed my previous python approach because blueman made a better
    def close(self):
+
  | version and it was outdated. Here is a node.js variant.
         url = self.addr + 'CloseSession/'
+
*/
         params = urllib.urlencode({
+
 
             'ID': self.sessionid
+
const readline = require('readline');
        })
+
var Client = require('node-rest-client').Client;
        print urllib2.urlopen(url, params).read()
+
var client = new Client();
+
var session_id;
     def do_cmd(self, cmd):
+
var base_url = "http://127.0.0.1:9000";
        url = self.addr + '/SessionCommand/'
+
 
         params = urllib.urlencode({
+
 
             'ID': self.sessionid,
+
// set http header
             'COMMAND': cmd
+
var headers = {
         })
+
    "Content-Type": "application/x-www-form-urlencoded",
         print urllib2.urlopen(url, params).read()
+
    "User-Agent": "nodejs-console/0.01"
+
};
     def read_buffer(self):
+
 
        url = self.addr + 'ReadResponses/' + self.sessionid + '/'
+
// open session
        params = urllib.urlencode({
+
function open_session() {
            'ID': self.sessionid
+
    var args = {
        })
+
        data: {
+
             "USER": "Test",
        print urllib2.urlopen(url, params).read()
+
             "PASS": 'secret'
+
         },
# set the base url to the REST console (with port)
+
         headers,
console = UserConsoleClient('<nowiki>http://127.0.0.1:8300/</nowiki>')
+
    };
console.read_buffer()
+
 
print 'quit with a "."'
+
    client.post(base_url + "/StartSession/", args, function (data, response) {
cmd = ""
+
        session_id = data.ConsoleSession.SessionID;
while cmd != ".":
+
        read_session_buffer();
     if cmd != "":
+
    });
        console.do_cmd(cmd)
+
}
        console.read_buffer()
+
 
     cmd = raw_input("> ")
+
// close session
+
function close_session() {
console.close()
+
    args = {
 +
        data: { "ID": session_id },
 +
        headers
 +
    };
 +
 
 +
    client.post(base_url + "/CloseSession/", args, function (data, response) {
 +
         console.log("close_session: "+response);
 +
    });
 +
 
 +
    console.log('Have a great day!');
 +
    process.exit(0);
 +
}
 +
 
 +
// read all the lines from the console buffer and print them
 +
function read_session_buffer() {
 +
    args = {
 +
        data: { "ID": session_id },
 +
         headers
 +
    };
 +
 
 +
    client.post(base_url + "/ReadResponses/"+session_id+"/", args, function (data, response) {
 +
         if(data.ConsoleSession.Line) {
 +
             var i;
 +
            for(i=0; i < data.ConsoleSession.Line.length; i++) {
 +
                if(data.ConsoleSession.Line[i]._) {
 +
                    console.log(data.ConsoleSession.Line[i]._);
 +
                }
 +
            }
 +
            rl.prompt();
 +
        }
 +
     });
 +
}
 +
 
 +
// execute the command from the prompt
 +
function execute_cmd(cmd) {
 +
    args = {
 +
         data: {
 +
             "ID": session_id,
 +
             "COMMAND": cmd
 +
         },
 +
         headers
 +
    };
 +
 
 +
    client.post(base_url + "/SessionCommand/", args, function (data, response) {
 +
     });
 +
}
 +
 
 +
 
 +
// here we go.
 +
open_session();
 +
 
 +
// prepare readline
 +
const rl = readline.createInterface({
 +
    input: process.stdin,
 +
    output: process.stdout,
 +
    prompt: 'REST CONSOLE> '
 +
});
 +
rl.prompt();
 +
 
 +
// hunt for events
 +
rl.on('line', (line) => {
 +
    switch (line.trim()) {
 +
        case 'quit':
 +
            close_session();
 +
            break;
 +
        default:
 +
            if(line.length > 0) {
 +
                execute_cmd(line.trim());
 +
            }
 +
            break;
 +
    }
 +
     read_session_buffer();
 +
    rl.prompt();
 +
}).on('close', () => {
 +
     close_session();
 +
});
 
</source>
 
</source>
 +
 
=== Python (Updated) ===
 
=== Python (Updated) ===
  
Line 201: Line 278:
  
 
=== JavaScript/HTML ===
 
=== JavaScript/HTML ===
<source lang="JavaScript">
+
 
 
<pre>
 
<pre>
 
<html>
 
<html>
Line 276: Line 353:
 
</pre>
 
</pre>
  
 +
 +
=== Python Alt===
 +
<source lang="python">
 +
#!/usr/bin/python
 +
# This piece of code is published by thomax (txOh) (c) 2010 under the
 +
# Artistic License 1.0 (http://www.perlfoundation.org/artistic_license_1_0)
 +
 +
import urllib, urllib2
 +
import xml.dom.minidom
 +
 +
class UserConsoleClient():
 +
 +
    def __init__(self, addr):
 +
        self.addr = addr
 +
        url = self.addr + 'StartSession/'
 +
 +
        params = urllib.urlencode({
 +
            'USER': 'Test',        # REST username
 +
            'PASS': 'secret'        # REST password
 +
        })
 +
        data = urllib2.urlopen(url, params).read()
 +
 +
        dom = xml.dom.minidom.parseString(data)
 +
        elem =  dom.getElementsByTagName('SessionID')
 +
        self.sessionid = elem[0].childNodes[0].nodeValue
 +
 +
    def close(self):
 +
        url = self.addr + 'CloseSession/'
 +
        params = urllib.urlencode({
 +
            'ID': self.sessionid
 +
        })
 +
        print urllib2.urlopen(url, params).read()
 +
 +
    def do_cmd(self, cmd):
 +
        url = self.addr + '/SessionCommand/'
 +
        params = urllib.urlencode({
 +
            'ID': self.sessionid,
 +
            'COMMAND': cmd
 +
        })
 +
        print urllib2.urlopen(url, params).read()
 +
 +
    def read_buffer(self):
 +
        url = self.addr + 'ReadResponses/' + self.sessionid + '/'
 +
        params = urllib.urlencode({
 +
            'ID': self.sessionid
 +
        })
 +
 +
        print urllib2.urlopen(url, params).read()
 +
 +
# set the base url to the REST console (with port)
 +
console = UserConsoleClient('<nowiki>http://127.0.0.1:8300/</nowiki>')
 +
console.read_buffer()
 +
print 'quit with a "."'
 +
cmd = ""
 +
while cmd != ".":
 +
    if cmd != "":
 +
        console.do_cmd(cmd)
 +
        console.read_buffer()
 +
    cmd = raw_input("> ")
 +
 +
console.close()
 
</source>
 
</source>
  
 
[[Category:German Translations]]
 
[[Category:German Translations]]

Revision as of 07:42, 15 July 2018

Contents

Über

Die REST-Konsole macht Remote-Administration der verschiedenen Open Dienste möglich.

Die Schnittstelle ermöglicht Befehle an den Server und Abrufen von Befehlsausgabe zu senden. Senden und Empfangen von Daten über RESTful HTTP-Aufrufe erfolgen.

Während das Senden sehr einfach ist, wird nicht mit. Empfangen verwendet HTTP-Reverse, eine lange Umfrage zu einer CAPS URI durchführen.

Um das Protokoll effizienter zu gestalten, die Hilfefunktion zu machen wurde auf der Client-Seite geschoben. Anstatt jeden Tastendruck an den Server senden, werden nur validierte Befehlszeilen gesendet. Um dies möglich zu machen, sendet der Server eine Burst-on-Connect von Daten, die der Baum der erlaubten Befehle und deren Hilfeinformationen. Dies kann durch den Kunden verwendet werden, um die "Hilfe" Befehlsausgabe sowohl lokal als auch zu schaffen als Kommandozeilen-Hilfe interaktiv zur Verfügung stellen.

Die Probe Konsolen-Client, OpenSim.ConsoleClient.exe, zeigt, wie das gemacht wird.

Verwendung

Um die Remote - Konsole zu verwenden, starten Sie Open Dienste mit dem Parameter -console rest.

Beispiel für Robust-Server im Grid-Modus:

mono Robust.exe -console rest

Beispiel für Simulatoren (sowohl im Grid und Standalone-Modus):

mono OpenSim.exe -console rest

Syntax

Wir nehmen die Opensimulator Dienstleistungsadresse http://MeinServer.de:8002 als Beispiel.

Zunächst eine neue Sitzung starten, indem Sie eine HTTP-POST-Anforderung senden.
Benutzername und Passwort sollten die gleichen Einstellungen sein,
wie für ConsoleUser und ConsolePass im Abschnitt [Network] der OpenSim.ini.

Parameter: USER, PASS

http://MeinServer.de:8002/StartSession/

Rückgabe: (XML) <ConsoleSession><SessionID></SessionID><Prompt></Prompt></ConsoleSession>

Jetzt haben wir die SessionID, die wir verwenden können um einen Befehl zu senden und zu empfangen.
Zuerst wird der Puffer Rückholung Konsole abrufen.
Parameter: keine

http://MeinServer.de:8002/ReadResponses/<SessionID>/

Rückgabe: (XML) <ConsoleSession><Line Number=x></Line></ConsoleSession>

Die Antwort enthält alle lines die derzeit im Puffer sind.
Nachfolgende Abrufe werden nur neue Zeilen abzurufen.
Der Abruf wird für bis zu 30 Sekunden lang gehalten, wenn es keine Daten gibt, dann kommt ein Fehler zurück.
Der Client wird voraussichtlich wieder ein Polling versuchen.

Verwenden Sie die Sitzungs-ID als Parameter, und senden Sie erneut eine POST-Anfrage.
Parameter: ID, COMMAND

http://MeinServer.de:8002/SessionCommand/

Rückgabe: (XML) <ConsoleSession><Result></Result></ConsoleSession>
Wenn alles gut gegangen ist, sollte der Befehl ausgeführt worden sind. Versuchen Sie einen anderen Befehl.

Wenn Sie die Verbindung zu schließen möchten, senden Sie erneut eine POST-Anfrage. Parameter: ID

http://MeinServer.de:8002/CloseSession/

Rückgabe: (XML) <ConsoleSession><Result></Result></ConsoleSession>
Die Sitzung ist geschlossen, und Sie müssen sich erneut anmelden, wenn Sie wollen, erneut einen Befehl zu senden.

Clients

C#

A C# client is included with the Opensimulator distribution. It is rudimentary and not updated to the latest protocol versions.

Qt

The Qt 5 based client is at https://github.com/MelanieT/OpenSimConsoleClient

Binaries

Windows: http://opensimulator.org/downloads/ConsoleClient.zip
Mac: http://opensimulator.org/downloads/ConsoleClient.dmg
Linux: TBD

Beispiele

HINWEIS

Some of the examples below are for an older version of the interface. They may work to a degree but need to be revised.

node.js

/*
 | This piece of code is published by thomax (tx0h) (c) 2018 under the
 | Artistic License 1.0 (http://www.perlfoundation.org/artistic_license_1_0)
 |
 | I removed my previous python approach because blueman made a better
 | version and it was outdated. Here is a node.js variant.
*/
 
const readline = require('readline');
var Client = require('node-rest-client').Client;
var client = new Client();
var session_id;
var base_url = "http://127.0.0.1:9000";
 
 
// set http header
var headers = {
    "Content-Type": "application/x-www-form-urlencoded",
    "User-Agent": "nodejs-console/0.01"
};
 
// open session
function open_session() {
    var args = {
        data: {
            "USER": "Test",
            "PASS": 'secret'
        },
        headers,
    };
 
    client.post(base_url + "/StartSession/", args, function (data, response) {
        session_id = data.ConsoleSession.SessionID;
        read_session_buffer();
    });
}
 
// close session
function close_session() {
    args = {
        data: { "ID": session_id },
        headers
    };
 
    client.post(base_url + "/CloseSession/", args, function (data, response) {
        console.log("close_session: "+response);
    });
 
    console.log('Have a great day!');
    process.exit(0);
}
 
// read all the lines from the console buffer and print them
function read_session_buffer() {
    args = {
        data: { "ID": session_id },
        headers
    };
 
    client.post(base_url + "/ReadResponses/"+session_id+"/", args, function (data, response) {
        if(data.ConsoleSession.Line) {
            var i;
            for(i=0; i < data.ConsoleSession.Line.length; i++) {
                if(data.ConsoleSession.Line[i]._) {
                    console.log(data.ConsoleSession.Line[i]._);
                }
            }
            rl.prompt();
        }
    });
}
 
// execute the command from the prompt
function execute_cmd(cmd) {
    args = {
        data: {
            "ID": session_id,
            "COMMAND": cmd
        },
        headers
    };
 
    client.post(base_url + "/SessionCommand/", args, function (data, response) {
    });
}
 
 
// here we go.
open_session();
 
// prepare readline
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    prompt: 'REST CONSOLE> '
});
rl.prompt();
 
// hunt for events
rl.on('line', (line) => {
    switch (line.trim()) {
        case 'quit':
            close_session();
            break;
        default:
            if(line.length > 0) {
                execute_cmd(line.trim());
            }
            break;
    }
    read_session_buffer();
    rl.prompt();
}).on('close', () => {
    close_session();
});

Python (Updated)

#!/usr/bin/python
# This piece of code is published by thomax (txOh) (c) 2010 under the
# Artistic License 1.0 (http://www.perlfoundation.org/artistic_license_1_0)
# Modifications (c) 2013 BlueWall
 
import urllib, urllib2
import xml.dom.minidom
 
class UserConsoleClient():
 
   def __init__(self, addr):
       self.addr = addr
       url = self.addr + 'StartSession/'
 
       params = urllib.urlencode({
           'USER': 'username',       # REST username
           'PASS': 'userpass'        # REST password
       })
       data = urllib2.urlopen(url, params).read()
       print data
 
       dom = xml.dom.minidom.parseString(data)
       elem =  dom.getElementsByTagName('SessionID')
       self.sessionid = elem[0].childNodes[0].nodeValue
       elem = dom.getElementsByTagName('Prompt')
       self.prompt = elem[0].childNodes[0].nodeValue + '# '
 
   def close(self):
       url = self.addr + 'CloseSession/'
       params = urllib.urlencode({
           'ID': self.sessionid
       })
       print urllib2.urlopen(url, params).read()
 
   def do_cmd(self, cmd):
       url = self.addr + 'SessionCommand/'
       params = urllib.urlencode({
           'ID': self.sessionid,
           'COMMAND': cmd
       })
       data = urllib2.urlopen(url, params).read()
       dom = xml.dom.minidom.parseString(data)
       elem =  dom.getElementsByTagName('Result')
       return elem[0].childNodes[0].nodeValue
 
   def read_buffer(self):
       url = self.addr + 'ReadResponses/' + self.sessionid + '/'
       params = urllib.urlencode({
           'ID': self.sessionid
       })
 
       # print urllib2.urlopen(url, params).read()
 
       result = urllib2.urlopen(url, params).read()
       dom = xml.dom.minidom.parseString(result)
 
       elem =  dom.getElementsByTagName('Line')
       for line in elem:
         x0 = line.childNodes[0].nodeValue
         x1 = str.replace(str(x0),':','~',2)
         x2 = x1.split("~")
         for lv in x2[2:]:
           if not '+++' in lv:
             print lv
 
# set the base url to the REST console (with port)
console = UserConsoleClient('http://example.com:8003/')
console.read_buffer()
print 'quit with a "."'
cmd = ""
while cmd != ".":
   if cmd != "":
     if 'OK' in console.do_cmd(cmd):
       console.read_buffer()
   cmd = raw_input("%s " % console.prompt)
 
console.close()

JavaScript/HTML

<html>
  <head>

    <!-- This JavaScript code is published by Marck (c) 2010 under a -->
    <!-- Creative Commons Attribution 3.0 Germany License            -->
    <!-- http://creativecommons.org/licenses/by/3.0/de/              -->
    <script type="text/javascript">

      var sessionId;
      var hostUrl;

      function StartSession(url, user, password) {
        hostUrl = url;
        var response = SendRequest("/StartSession/", "USER=" + user + "&PASS=" + password);
        sessionId = response.getElementsByTagName("SessionID")[0].firstChild.nodeValue;
      };

      function ReadResponses() {
        var response = this.SendRequest("/ReadResponses/" + sessionId + "/", '');
        var lines = response.getElementsByTagName("Line");
        for (var i = 0; i < lines.length; ++i) {
          var element = document.createElement("div");
          element.appendChild(document.createTextNode(lines[i].firstChild.nodeValue));
          document.getElementById("output").appendChild(element);
        };
        document.getElementById("output").scrollTop = document.getElementById("output").scrollHeight;
      };

      function Command(cmd) {
        void SendRequest("/SessionCommand/", "ID=" + sessionId + "&COMMAND=" + cmd);
      };

      function CloseSession() {
        void SendRequest("/CloseSession/", "ID=" + sessionId);
      };

      function SendRequest(path, data) {
        var request = new XMLHttpRequest();
        request.open("POST", hostUrl + path, false);
        request.send(data);
        return request.responseXML;
      };

      window.onunload = CloseSession;

    </script>
  </head>
  <body>

    <form action="#" onsubmit="
        StartSession(this.address.value, this.user.value, this.password.value);
        ReadResponses();
        return false">
      <input name="address" type="text" value="http://localhost:9000" />
      <input name="user" type="text" value="ConsoleUser" />
      <input name="password" type="text" value="ConsolePass" />
      <input type="submit" value="Login" />
    </form>

    <div id="output" style="height:15em; border:thin solid; overflow:auto;"></div>

    <form action="#" onsubmit="
        Command(this.command.value);
        ReadResponses();
        return false">
      <input type="text" name="command" value="Enter command here" size="40"/>
      <input type="submit" value="Send Command" />
    </form>

  </body>
</html>


Python Alt

#!/usr/bin/python
 # This piece of code is published by thomax (txOh) (c) 2010 under the
 # Artistic License 1.0 (http://www.perlfoundation.org/artistic_license_1_0)
 
 import urllib, urllib2
 import xml.dom.minidom
 
 class UserConsoleClient():
 
    def __init__(self, addr):
        self.addr = addr
        url = self.addr + 'StartSession/'
 
        params = urllib.urlencode({
            'USER': 'Test',         # REST username
            'PASS': 'secret'        # REST password
        })
        data = urllib2.urlopen(url, params).read()
 
        dom = xml.dom.minidom.parseString(data)
        elem =  dom.getElementsByTagName('SessionID')
        self.sessionid = elem[0].childNodes[0].nodeValue
 
    def close(self):
        url = self.addr + 'CloseSession/'
        params = urllib.urlencode({
            'ID': self.sessionid
        })
        print urllib2.urlopen(url, params).read()
 
    def do_cmd(self, cmd):
        url = self.addr + '/SessionCommand/'
        params = urllib.urlencode({
            'ID': self.sessionid,
            'COMMAND': cmd
        })
        print urllib2.urlopen(url, params).read()
 
    def read_buffer(self):
        url = self.addr + 'ReadResponses/' + self.sessionid + '/'
        params = urllib.urlencode({
            'ID': self.sessionid
        })
 
        print urllib2.urlopen(url, params).read()
 
 # set the base url to the REST console (with port)
 console = UserConsoleClient('<nowiki>http://127.0.0.1:8300/</nowiki>')
 console.read_buffer()
 print 'quit with a "."'
 cmd = ""
 while cmd != ".":
    if cmd != "":
        console.do_cmd(cmd)
        console.read_buffer()
    cmd = raw_input("> ")
 
 console.close()
Personal tools
General
About This Wiki