Advertisement
Guest User

Untitled

a guest
May 29th, 2018
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. # encoding: utf-8
  2.  
  3. """ Python General Helpers
  4. Copyright (c) 2010 Kenneth Reitz. Creative Commons Attribution 3.0 License.
  5. """
  6.  
  7. import urllib, re, time, sys
  8. import paramiko
  9.  
  10.  
  11. class Object(object):
  12. """Your attributes are belong to us."""
  13.  
  14. def __init__(self, **entries):
  15. self.__dict__.update(entries)
  16. def __getitem__(self, key):
  17. return getattr(self, key)
  18.  
  19.  
  20.  
  21. def iscollection(obj):
  22. """Tests if an object is a collection"""
  23.  
  24. col = getattr(obj, '__getitem__', False)
  25. val = False if (not col) else True
  26.  
  27. if isstring(obj):
  28. val = False
  29.  
  30. return val
  31.  
  32.  
  33. def isstring(obj):
  34. """Tests if an object is a string"""
  35.  
  36. return True if type(obj).__name__ == 'str' else False
  37.  
  38. def print_args(function):
  39. def wrapper(*args, **kwargs):
  40. print 'Arguments:', args, kwargs
  41. return function(*args, **kwargs)
  42. return wrapper
  43.  
  44.  
  45. def enc(str):
  46. """Encodes a string to ascii"""
  47.  
  48. return str.encode('ascii', 'ignore')
  49.  
  50.  
  51. def dec(str):
  52. """Decodes a string to ascii"""
  53.  
  54. return str.decode('ascii', 'ignore')
  55.  
  56.  
  57. def get_file(path):
  58. """Returns a file as a string"""
  59.  
  60. return open(path, 'r').read()
  61.  
  62.  
  63. def get_file_lines(path):
  64. """Returns a file as a list of strings"""
  65.  
  66. return open(path, 'r').readlines()
  67.  
  68.  
  69. def get_http(uri):
  70. """Fetches a file over http as a string"""
  71.  
  72. return urllib.urlopen(uri).read()
  73.  
  74.  
  75. def get_http_lines(uri):
  76. """Fetches a file over http as a file object"""
  77.  
  78. return urllib.urlopen(uri).readlines()
  79.  
  80.  
  81. def get_sftp(hostname, username, password, filename):
  82. """Fetches a file over sftp as a string
  83. Note: Server must be in known_hosts.
  84. """
  85.  
  86. client = paramiko.SSHClient()
  87. print("Download of %s started" % filename)
  88. client.load_host_keys('/root/.ssh/known_hosts')
  89. client.connect(hostname=hostname, username=username, password=password)
  90. file = client.open_sftp().open(filename).read()
  91. print("Download of %s complete" % filename)
  92.  
  93. return file
  94.  
  95. def get_piped():
  96. """Returns piped input via stdin, else False"""
  97.  
  98. with sys.stdin as stdin:
  99. return stdin.read() if not stdin.isatty() else None
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement