Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/bareos/python-bareos.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJoerg Steffens <joerg.steffens@bareos.com>2016-04-25 16:37:43 +0300
committerJoerg Steffens <joerg.steffens@bareos.com>2016-04-25 16:37:43 +0300
commit3c3b7a5da5c3f370b5a75bf5a0295ebe4c660acb (patch)
tree9d4826d547bffe635a5bfac4da7caf01ee8ceb23
parenta92ba26db9a83875115fd3c7fe01749758097db0 (diff)
PYthon 3: use bytearrays instead of strings (str)
Should work with Python 2 (>= 2.6) and Python 3.
-rw-r--r--bareos/bsock/bsock.py13
-rwxr-xr-xbareos/bsock/bsockjson.py11
-rw-r--r--bareos/bsock/lowlevel.py40
-rw-r--r--bareos/bsock/protocolmessages.py8
-rw-r--r--bareos/util/bareosbase64.py8
-rw-r--r--bareos/util/password.py4
-rwxr-xr-xbin/bconsole-json.py3
-rwxr-xr-xbin/bconsole.py3
8 files changed, 54 insertions, 36 deletions
diff --git a/bareos/bsock/bsock.py b/bareos/bsock/bsock.py
index d0fa3a8..e2357b8 100644
--- a/bareos/bsock/bsock.py
+++ b/bareos/bsock/bsock.py
@@ -35,9 +35,9 @@ class BSock(LowLevel):
Call a bareos-director user agent command.
If connection is lost, try to reconnect.
'''
- result = ''
+ result = b''
try:
- self.send(str(command))
+ self.send(bytearray(command, 'utf-8'))
result = self.recv_msg()
except (SocketEmptyHeader, ConnectionLostError) as e:
self.logger.error("connection problem (%s): %s" % (type(e).__name__, str(e)))
@@ -58,7 +58,12 @@ class BSock(LowLevel):
self._set_state_director_prompt()
command = ""
while command != "exit" and command != "quit":
- command = raw_input(">>")
+ # Python2: raw_input, Python3: input
+ try:
+ myinput = raw_input
+ except NameError:
+ myinput = input
+ command = myinput(">>")
resultmsg = self.call(command)
- sys.stdout.write(resultmsg)
+ sys.stdout.write(resultmsg.decode('utf-8'))
return True
diff --git a/bareos/bsock/bsockjson.py b/bareos/bsock/bsockjson.py
index a14622c..b23685b 100755
--- a/bareos/bsock/bsockjson.py
+++ b/bareos/bsock/bsockjson.py
@@ -26,7 +26,7 @@ class BSockJson(BSock):
json = self.call_fullresult(command)
if json == None:
return
- if json.has_key('result'):
+ if 'result' in json:
result = json['result']
else:
# TODO: or raise an exception?
@@ -38,8 +38,9 @@ class BSockJson(BSock):
resultstring = super(BSockJson, self).call(command)
data = None
if resultstring:
+ print(resultstring.decode('utf-8'))
try:
- data = json.loads(resultstring)
+ data = json.loads(resultstring.decode('utf-8'))
except ValueError as e:
# in case result is not valid json,
# create a JSON-RPC wrapper
@@ -60,7 +61,11 @@ class BSockJson(BSock):
self._set_state_director_prompt()
command = ""
while command != "exit" and command != "quit":
- command = raw_input(">>")
+ try:
+ myinput = raw_input
+ except NameError:
+ myinput = input
+ command = myinput(">>")
if command:
pprint(self.call(command))
return True
diff --git a/bareos/bsock/lowlevel.py b/bareos/bsock/lowlevel.py
index 75ac8c1..3695b65 100644
--- a/bareos/bsock/lowlevel.py
+++ b/bareos/bsock/lowlevel.py
@@ -115,7 +115,7 @@ class LowLevel(object):
try:
# convert to network flow
self.socket.sendall(struct.pack("!i", msg_len) + msg)
- self.logger.debug("%s" %(msg.encode('string-escape')))
+ self.logger.debug("%s" %(msg))
except socket.error as e:
self._handleSocketError(e)
@@ -136,7 +136,7 @@ class LowLevel(object):
def recv_msg(self):
'''will receive data from director '''
self.__check_socket_connection()
- msg = ""
+ msg = b""
try:
timeouts = 0
while True:
@@ -166,7 +166,7 @@ class LowLevel(object):
def recv_submsg(self, length):
# get the message
- msg = ""
+ msg = b""
while length > 0:
self.logger.debug(" submsg len: " + str(length))
# TODO
@@ -175,6 +175,10 @@ class LowLevel(object):
length -= len(submsg)
#self.logger.debug(submsg)
msg += submsg
+ if (type(msg) is str):
+ msg = bytearray(msg, 'utf-8')
+ if (type(msg) is bytes):
+ msg = bytearray(msg)
return msg
@@ -213,21 +217,23 @@ class LowLevel(object):
# to confirm the director so can do this on bconsole`way
rand = random.randint(1000000000, 9999999999)
#chal = "<%u.%u@%s>" %(rand, int(time.time()), self.dirname)
- chal = "<%u.%u@%s>" %(rand, int(time.time()), clientname)
- msg = 'auth cram-md5 %s ssl=%d\n' %(chal, tls_local_need)
+ chal = '<%u.%u@%s>' %(rand, int(time.time()), clientname)
+ msg = bytearray('auth cram-md5 %s ssl=%d\n' %(chal, tls_local_need), 'utf-8')
# send the confirmation
self.send(msg)
# get the response
- msg = self.recv().strip(chr(0))
- self.logger.debug("received: " + msg)
+ msg = self.recv()
+ if msg[-1] == 0:
+ del msg[-1]
+ self.logger.debug("received: " + str(msg))
# hash with password
- hmac_md5 = hmac.new(password)
- hmac_md5.update(chal)
+ hmac_md5 = hmac.new(bytearray(password, 'utf-8'))
+ hmac_md5.update(bytearray(chal, 'utf-8'))
bbase64compatible = BareosBase64().string_to_base64(bytearray(hmac_md5.digest()), True)
bbase64notcompatible = BareosBase64().string_to_base64(bytearray(hmac_md5.digest()), False)
- self.logger.debug("string_to_base64, compatible: " + bbase64compatible)
- self.logger.debug("string_to_base64, not compatible: " + bbase64notcompatible)
+ self.logger.debug("string_to_base64, compatible: " + str(bbase64compatible))
+ self.logger.debug("string_to_base64, not compatible: " + str(bbase64notcompatible))
is_correct = ((msg == bbase64compatible) or (msg == bbase64notcompatible))
# check against compatible base64 and Bareos specific base64
@@ -256,14 +262,14 @@ class LowLevel(object):
self.logger.error("RuntimeError exception in recv")
return (0, True, False)
# check the receive message
- self.logger.debug("(recv): " + msg.encode('string-escape'))
- msg_list = msg.split(" ")
+ self.logger.debug("(recv): " + str(msg))
+ msg_list = msg.split(b" ")
chal = msg_list[2]
# get th timestamp and the tle info from director response
ssl = int(msg_list[3][4])
compatible = True
# hmac chal and the password
- hmac_md5 = hmac.new(password)
+ hmac_md5 = hmac.new(bytearray(password, 'utf-8'))
hmac_md5.update(chal)
# base64 encoding
@@ -275,7 +281,7 @@ class LowLevel(object):
if ProtocolMessages.is_auth_ok(received):
result = True
else:
- self.logger.error("failed: " + received)
+ self.logger.error("failed: " + str(received))
return (ssl, compatible, result)
@@ -286,9 +292,9 @@ class LowLevel(object):
def _set_state_director_prompt(self):
- self.send(".")
+ self.send(b".")
msg = self.recv_msg()
- self.logger.debug("received message: " + msg)
+ self.logger.debug("received message: " + str(msg))
# TODO: check prompt
return True
diff --git a/bareos/bsock/protocolmessages.py b/bareos/bsock/protocolmessages.py
index b898a50..78fb3a9 100644
--- a/bareos/bsock/protocolmessages.py
+++ b/bareos/bsock/protocolmessages.py
@@ -11,9 +11,9 @@ class ProtocolMessages():
@staticmethod
def hello(name, type=ConnectionType.DIRECTOR):
if type == ConnectionType.FILEDAEMON:
- return "Hello Director %s calling\n" % (name)
+ return bytearray("Hello Director %s calling\n" % (name), 'utf-8')
else:
- return "Hello %s calling\n" % (name)
+ return bytearray("Hello %s calling\n" % (name), 'utf-8')
#@staticmethod
#def ok():
@@ -21,11 +21,11 @@ class ProtocolMessages():
@staticmethod
def auth_ok():
- return "1000 OK auth\n"
+ return b"1000 OK auth\n"
@staticmethod
def auth_failed():
- return "1999 Authorization failed.\n"
+ return b"1999 Authorization failed.\n"
@staticmethod
def is_auth_ok(msg):
diff --git a/bareos/util/bareosbase64.py b/bareos/util/bareosbase64.py
index a80e4f7..21bae65 100644
--- a/bareos/util/bareosbase64.py
+++ b/bareos/util/bareosbase64.py
@@ -19,7 +19,7 @@ class BareosBase64(object):
'''
Initialize the Base 64 conversion routines
'''
- self.base64_map = dict(zip(self.base64_digits, xrange(0, 64)))
+ self.base64_map = dict(list(zip(self.base64_digits, list(range(0, 64)))))
@staticmethod
def twos_comp(val, bits):
@@ -40,12 +40,12 @@ class BareosBase64(object):
neg = True
first = 1
- for i in xrange(first, len(base64)):
+ for i in range(first, len(base64)):
value = value << 6
try:
value += self.base64_map[base64[i]]
except KeyError:
- print "KeyError:", i
+ print("KeyError:", i)
return -value if neg else value
@@ -96,4 +96,4 @@ class BareosBase64(object):
buf += self.base64_digits[(reg & mask) << (6 - rem)]
else:
buf += self.base64_digits[reg & mask]
- return buf
+ return bytearray(buf, 'utf-8')
diff --git a/bareos/util/password.py b/bareos/util/password.py
index 37b56b4..99def12 100644
--- a/bareos/util/password.py
+++ b/bareos/util/password.py
@@ -11,7 +11,7 @@ class Password(object):
self.set_plaintext(password)
def set_plaintext(self, password):
- self.password_plaintext = password
+ self.password_plaintext = bytearray(password, 'utf-8')
self.set_md5(self.__plaintext2md5(password))
def set_md5(self, password):
@@ -29,5 +29,5 @@ class Password(object):
md5 the password and return the hex style
'''
md5 = hashlib.md5()
- md5.update(password)
+ md5.update(bytearray(password, 'utf-8'))
return md5.hexdigest()
diff --git a/bin/bconsole-json.py b/bin/bconsole-json.py
index 337412e..3cca0f2 100755
--- a/bin/bconsole-json.py
+++ b/bin/bconsole-json.py
@@ -1,5 +1,6 @@
#!/usr/bin/python
+from __future__ import print_function
import argparse
import bareos.bsock
import logging
@@ -38,7 +39,7 @@ if __name__ == '__main__':
parameter['password']=password
director = bareos.bsock.BSockJson(**parameter)
except RuntimeError as e:
- print str(e)
+ print(str(e))
sys.exit(1)
logger.debug( "authentication successful" )
director.interactive()
diff --git a/bin/bconsole.py b/bin/bconsole.py
index 810802f..1c8f0c8 100755
--- a/bin/bconsole.py
+++ b/bin/bconsole.py
@@ -1,5 +1,6 @@
#!/usr/bin/python
+from __future__ import print_function
import argparse
#import bareos
import bareos.bsock
@@ -39,7 +40,7 @@ if __name__ == '__main__':
parameter['password']=password
director = bareos.bsock.BSock(**parameter)
except RuntimeError as e:
- print str(e)
+ print(str(e))
sys.exit(1)
logger.debug( "authentication successful" )
director.interactive()