Advertisement
furas

python - ssh walk and search

Jun 20th, 2018
273
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.63 KB | None | 0 0
  1. class SSHSession(object):
  2.     # Usage:
  3.     # Detects DSA or RSA from key_file, either as a string filename or a
  4.     # file object.  Password auth is possible, but I will judge you for
  5.     # using it. So:
  6.     # ssh=SSHSession('targetserver.com','root',key_file=open('mykey.pem','r'))
  7.     # ssh=SSHSession('targetserver.com','root',key_file='/home/me/mykey.pem')
  8.     # ssh=SSHSession('targetserver.com','root','mypassword')
  9.     # ssh.put('filename','/remote/file/destination/path')
  10.     # ssh.put_all('/path/to/local/source/dir','/path/to/remote/destination')
  11.     # ssh.get_all('/path/to/remote/source/dir','/path/to/local/destination')
  12.     # ssh.command('echo "Command to execute"')
  13.  
  14.     def __init__(self,hostname,username='root',key_file=None,password=None):
  15.         #
  16.         #  Accepts a file-like object (anything with a readlines() function)
  17.         #  in either dss_key or rsa_key with a private key.  Since I don't
  18.         #  ever intend to leave a server open to a password auth.
  19.         #
  20.         self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  21.         self.sock.connect((hostname,22))
  22.         self.t = paramiko.Transport(self.sock)
  23.         self.t.start_client()
  24.         keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
  25.         key = self.t.get_remote_server_key()
  26.         # supposed to check for key in keys, but I don't much care right now to find the right notation
  27.         if key_file is not None:
  28.             if isinstance(key,str):
  29.                 key_file=open(key,'r')
  30.             key_head=key_file.readline()
  31.             key_file.seek(0)
  32.             if 'DSA' in key_head:
  33.                 keytype=paramiko.DSSKey
  34.             elif 'RSA' in key_head:
  35.                 keytype=paramiko.RSAKey
  36.             else:
  37.                 raise Exception("Can't identify key type")
  38.             pkey=keytype.from_private_key(key_file)
  39.             self.t.auth_publickey(username, pkey)
  40.         else:
  41.             if password is not None:
  42.                 self.t.auth_password(username,password,fallback=False)
  43.             else: raise Exception('Must supply either key_file or password')
  44.         self.sftp=paramiko.SFTPClient.from_transport(self.t)
  45.  
  46.  
  47.     def remote_walk(self, remotepath):
  48.         dirs = []
  49.         #files = []
  50.  
  51.         for f in self.sftp.listdir_attr(remotepath):
  52.             if S_ISDIR(f.st_mode):
  53.                 if f.filename != '.' and f.filename != '..':
  54.                     dirs.append(f.filename)
  55.             #else:
  56.             #    files.append(f.filename)
  57.  
  58.         #return dirs, files
  59.         return dirs
  60.  
  61.  
  62.     def find_folder(self, remotepath, foldername):
  63.         print("find_folder:", remotepath, foldername)
  64.        
  65.         dirs = self.remote_walk(remotepath)
  66.        
  67.         if foldername in dirs:
  68.            return os.path.join(remotepath, foldername)
  69.         else:
  70.             print("I am trying to find in child directories")
  71.             for subfolder in dirs:
  72.                 subfolder_fullpath = os.path.join(remotepath, subfolder)
  73.                 print("subfolder:", subfolder)
  74.                 result = self.find_folder(subfolder_fullpath, foldername)
  75.                 # if found path then return it (in recursion)
  76.                 if results:
  77.                     return result
  78.                 # else go back to `for` and check next subfolder
  79.  
  80.         #return None # it automatically returns None if can't find folder
  81.  
  82.  
  83. ###################################################
  84. sshobject = SSHSession(hostname=host_name, username=test_user, key_file=None, password=test_password)
  85. sshobject.find_folder(remotepath=str(base_dir), foldername="folder_name_to_search")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement