Advertisement
Guest User

Untitled

a guest
Mar 15th, 2018
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.04 KB | None | 0 0
  1. def read_file(pathfile):
  2.     with open(pathfile, 'r', encoding='utf-8') as file:
  3.         return file.read()
  4.  
  5.  
  6. def read_file_by_lines(pathfile):
  7.     with open(pathfile, 'r', encoding='utf-8') as file:
  8.         for file_line in file:
  9.             print(file_line)
  10.  
  11.  
  12. def write_file(pathfile, value):
  13.     with open(pathfile, 'a', encoding='utf-8') as file:
  14.         return file.write(value)
  15.  
  16.  
  17.  
  18. (
  19.     pl_guess, pl_int, pl_hex, pl_hexu, pl_hexl, pl_hexu_space, pl_hexl_space, pl_asc, pl_ut8,
  20.     pl_lint, pl_lasc, pl_lut8, pl_asc_lint, pl_asc_lhex, pl_all
  21. ) = range(15)
  22.  
  23.  
  24. def _asc_to_lint(data):
  25.     return list(data.encode('ascii', 'replace'))
  26.  
  27. def _ut8_to_lint(data):
  28.     return list(data.encode('utf-8', 'replace'))
  29.  
  30. def _lasc_to_lint(datas):
  31.     data = ''.join(datas)
  32.     return list(data.encode('ascii', 'replace'))
  33.  
  34. def _lut8_to_lint(datas):
  35.     data = ''.join(datas)
  36.     return list(data.encode('utf-8', 'replace'))
  37.  
  38. def _int_to_lint(data):
  39.     lint = []
  40.     while data:
  41.         lint.insert(0, data % 256)
  42.         data = data // 256
  43.     return lint
  44.  
  45. def _hex_to_lint(data):
  46.     hex_digits_half_1 = data[::2]
  47.     hex_digits_half_2 = data[1::2]
  48.     hex_digits = zip(hex_digits_half_1, hex_digits_half_2)
  49.     lint = [
  50.         int('%s%s' % (dig_1, dig_2), 16)
  51.         for dig_1, dig_2
  52.         in hex_digits ]
  53.     return list(lint)
  54.  
  55. def _asc_lint_to_lint(asc_lint):
  56.     asc_lint = asc_lint.translate(str.maketrans(",.-_;", "     "))
  57.     asc_lint_splitted = asc_lint.split()
  58.     return list([int(elem) for elem in asc_lint_splitted])
  59.  
  60. def _asc_lhex_to_lint(asc_lhex):
  61.     asc_lhex = asc_lhex.translate(str.maketrans(",.-_;", "     "))
  62.     asc_lhex_splitted = asc_lhex.split()
  63.     return list([int(elem, 16) for elem in asc_lhex_splitted])
  64.  
  65.  
  66. def _lint_to_int(lint):
  67.     big_int = 0
  68.     for cur_int in lint:
  69.         big_int *= 256
  70.         big_int += cur_int
  71.     return str(big_int)
  72.  
  73. def _lint_to_lhex(lint):
  74.     lhex = [
  75.         hex(cur_int)[2:].rjust(2, '0')
  76.         for cur_int in lint
  77.     ]
  78.     return lhex
  79.  
  80. def _lint_to_hexu(lint):
  81.     lhex = _lint_to_lhex(lint)
  82.     return ''.join(lhex).upper()
  83.  
  84. def _lint_to_hexl(lint):
  85.     lhex = _lint_to_lhex(lint)
  86.     return ''.join(lhex).lower()
  87.  
  88. def _lint_to_hexu_space(lint):
  89.     lhex = _lint_to_lhex(lint)
  90.     return ' '.join(lhex).upper()
  91.  
  92. def _lint_to_hexl_space(lint):
  93.     lhex = _lint_to_lhex(lint)
  94.     return ' '.join(lhex).lower()
  95.  
  96. def _lint_to_asc(lint):
  97.     return str((bytes(lint)).decode("ascii", "replace"))
  98.  
  99. def _lint_to_ut8(lint):
  100.     return str((bytes(lint)).decode("utf-8", "replace"))
  101.  
  102.  
  103. DICT_FUNCTION_IN_FROM_PL_TYPE = {
  104.     pl_int: _int_to_lint,
  105.     pl_hex: _hex_to_lint,
  106.     pl_hexu: _hex_to_lint,
  107.     pl_hexl: _hex_to_lint,
  108.     pl_asc: _asc_to_lint,
  109.     pl_ut8: _ut8_to_lint,
  110.     pl_lint: lambda data: data,
  111.     pl_lasc: _lasc_to_lint,
  112.     pl_lut8: _lut8_to_lint,
  113.     pl_asc_lint: _asc_lint_to_lint,
  114.     pl_asc_lhex: _asc_lhex_to_lint,
  115. }
  116.  
  117. DICT_FUNCTION_OUT_FROM_PL_TYPE = {
  118.     pl_int: ('entier', _lint_to_int),
  119.     pl_hexu: ('hexa upcase', _lint_to_hexu),
  120.     pl_hexl: ('hexa lowcase', _lint_to_hexl),
  121.     pl_hexu_space: ('hexa-space upcase', _lint_to_hexu_space),
  122.     pl_hexl_space: ('hexa-space lowcase', _lint_to_hexl_space),
  123.     pl_asc: ('str ascii', _lint_to_asc),
  124.     pl_ut8: ('str utf-8', _lint_to_ut8),
  125.     pl_lint: ('liste entier', lambda data: str(data)),
  126. }
  127.  
  128. PL_TYPES_FOR_PL_ALL = (pl_int, pl_lint, pl_hexu, pl_hexl, pl_hexu_space, pl_hexl_space, pl_asc, pl_ut8)
  129.  
  130. label_length_max = max([
  131.     len(value[0])
  132.     for key, value
  133.     in DICT_FUNCTION_OUT_FROM_PL_TYPE.items()
  134. ])
  135.  
  136.  
  137. def _only_allowed_chars(str_data, allowed_chars):
  138.     unauthorized_chars = set(str_data) - set(allowed_chars)
  139.     return not bool(unauthorized_chars)
  140.  
  141. def _guess(data):
  142.     if isinstance(data, (list, tuple)):
  143.         if all([ isinstance(elem, int) for elem in data ]):
  144.             return pl_lint
  145.         if all([ isinstance(elem, str) for elem in data ]):
  146.             data = ''.join(data)
  147.             # Pas de détection d'encodage. C'est ascii ou utf-8. Tant pis si ça pète après.
  148.             try:
  149.                 data.encode('ascii')
  150.                 return pl_lasc
  151.             except:
  152.                 return pl_lut8
  153.  
  154.     if isinstance(data, str):
  155.         if _only_allowed_chars(data, '0123456789abcdefABCDEF'):
  156.             return pl_hex
  157.         if _only_allowed_chars(data, ',.-_;0123456789 '):
  158.             return pl_asc_lint
  159.         if _only_allowed_chars(data, ',.-_;0123456789 abcdefABCDEF'):
  160.             return pl_asc_lhex
  161.         # Toujours pas de détection d'encodage
  162.         try:
  163.             data.encode('ascii')
  164.             return pl_asc
  165.         except:
  166.             return pl_ut8
  167.  
  168.     if isinstance(data, int):
  169.         return pl_int
  170.  
  171.     return None
  172.  
  173.  
  174. def plop(data, pl_type_out=pl_all, pl_type_in=pl_guess):
  175.  
  176.     if pl_type_in == pl_guess:
  177.         pl_type_in = _guess(data)
  178.     if pl_type_in is None:
  179.         raise Exception("Fail guess")
  180.     function_in = DICT_FUNCTION_IN_FROM_PL_TYPE.get(pl_type_in)
  181.     if pl_type_in is None:
  182.         raise Exception("Fail arguments pl_type_in")
  183.     lint = function_in(data)
  184.  
  185.     if pl_type_out == pl_all:
  186.         print('')
  187.         for pl_type_out_current in PL_TYPES_FOR_PL_ALL:
  188.             label, function_out = DICT_FUNCTION_OUT_FROM_PL_TYPE[pl_type_out_current]
  189.             try:
  190.                 print('%s : %s' % (label.ljust(label_length_max), function_out(lint)))
  191.             except:
  192.                 print('%s : %s' % (label.ljust(label_length_max), 'fail'))
  193.             print('')
  194.  
  195.     else:
  196.         out_infos = DICT_FUNCTION_OUT_FROM_PL_TYPE.get(pl_type_out)
  197.         if out_infos is None:
  198.             raise Exception("Fail arguments pl_type_out")
  199.         function_out = out_infos[1]
  200.         return function_out(lint)
  201.  
  202.  
  203. # snippets de code pour faire du ssh et du snmp à travers un rebond ssh.
  204.  
  205. #   def start_ssh():
  206. #       self.ssh_client = paramiko.SSHClient()
  207. #       self.ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  208. #       # https://docs.python.org/2/library/getpass.html
  209. #       password = getpass.getpass('Veuillez entrer le mot de passe pour la connexion SSH : ')
  210. #       self.ssh_client.connect(ip, port=port, username=username, password=password)
  211. #
  212. #   def config(
  213. #       self, version='v2c', community='NAGIOS', walker_ip='1.2.3.4', walker_port=5050,
  214. #       oid_prefix_in='1.3.6.1.4.1.42229.6.22.', line_prefix_out='SNMPv2-SMI::enterprises.42229.6.22.'
  215. #   ):
  216. #       """
  217. #       Le oid_prefix_in doit se terminer par un '.', sinon ça ne marche pas.
  218. #       Le line_prefix_out doit correspondre à l'oid_prefix_in.
  219. #       """
  220. #       self.version = version
  221. #       self.community = community
  222. #       self.walker_ip = walker_ip
  223. #       self.walker_port = walker_port
  224. #       self.oid_prefix_in = oid_prefix_in
  225. #       self.line_prefix_out = line_prefix_out
  226. #       param_commands = (self.version, self.community, self.walker_ip, str(self.walker_port))
  227. #       self._walk_commmand = 'snmpwalk -%s -c %s %s:%s ' % param_commands
  228. #       self._get_commmand = 'snmpget -%s -c %s %s:%s ' % param_commands
  229. #       self._set_commmand = 'snmpset -%s -c %s %s:%s ' % param_commands
  230. #
  231. #   def test(self):
  232. #       stdin, stdout, stderr = self.ssh_client.exec_command('ls -l')
  233. #       logger.info(''.join(stdout))
  234.  
  235.  
  236. if __name__ == '__main__':
  237.  
  238.     plop(123456)
  239.     print('-' * 10)
  240.     plop('deadBEEF')
  241.     print('-' * 10)
  242.     plop('tralala;$_pouet')
  243.     print('-' * 10)
  244.     plop('abcdéèê')
  245.     print('-' * 10)
  246.     plop('αβ')
  247.     print('-' * 10)
  248.     plop(list(range(41)))
  249.     print('-' * 10)
  250.     plop(('a', 'b', 'c'))
  251.     print('-' * 10)
  252.     plop(('é', 'è', 'ñ'))
  253.     print('-' * 10)
  254.  
  255.     print(plop('deadbeef', pl_lint, pl_hex))
  256.     print('-' * 10)
  257.  
  258.     # Bof... Mais on n'a pas besoin de ça.
  259.     plop('a1,b2,100')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement