Advertisement
Guest User

Basic Linux Administration

a guest
Jun 17th, 2015
1,345
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.04 KB | None | 0 0
  1.  
  2. # Import a couple of modules
  3.  
  4. import paramiko     # For High level  networking
  5. import os       # Basic shell usage
  6. import getpass      # Allows user input without echoing
  7. import sys      # Allows basic system commands
  8. import time     # Works with local time
  9.    
  10.  
  11. # Initialise the class as an object. Create a couple of functions inside.
  12. # __init__ is present in every class, Instantiation which occurs before any function is called
  13. # Even if __init__ properties arent specified, it still exists.
  14.  
  15. class startUP(object):
  16.  
  17.     def __init__(self):
  18.    
  19.     execComm = execCommand()
  20.  
  21.  
  22. class execCommand(object):
  23.  
  24. # Set a couple of global class variables and clear the shell
  25.  
  26.  
  27.     os.system(['clear', 'cls'][os.name == 'nt'])
  28.  
  29.     _host = raw_input("\n\n[!] Please Enter Remote IP: ")
  30.     _port = raw_input("[!] Please Enter Target Port: ")
  31.     _port = int(_port)
  32.     _uname = raw_input("[!] Please Enter Target Username: ")
  33.     _passwd = getpass.getpass("[!] Please Enter Target Password: ")
  34.    
  35.  
  36. # Example of multi line printing
  37.  
  38.     def __init__(self):
  39.      print(''' 
  40.                     __         __
  41.                    (  ) _ - _ (  )
  42.                     ~~         ~~
  43.                      (  0   0  )
  44.        --------ooO----(       )----Ooo--------
  45.                """     (     )     """
  46.                         (   )
  47.                          \ /
  48.                         ~~O~~
  49. \n''')
  50.  
  51. # Print a few options to screen, pairing data structures together with the zip function creating a menu
  52.      
  53.          print('\n\nJoin me in the sewers...\nIt may be time to search for RATs\n\n')
  54.      
  55.      self._Item = ['Menu', '1', '2', '0']
  56.      self._Desc = ['Job List\n\n', 'Bad Samaritan', 'Retrieval Job\n', 'Great Escape\n']
  57.          
  58.      for q, a in zip(self._Item, self._Desc):
  59.         print('{0}: The {1}'.format(q, a))
  60.  
  61.  
  62. # Ask for user input and set the received value as an integer.        
  63.  
  64.          self._Choice = raw_input('Tell Me What To Do..: ')
  65.          self._Choice = int(self._Choice)
  66.  
  67. # Function Variables
  68.      
  69.      self._List = str('')
  70.          self. _Str = str(self._List)
  71.      self._UI = str('')
  72.  
  73. # Basic if, else if and else sequence. Various different functions are called depending on response
  74.  
  75.      try:
  76.              
  77.              if self._Choice == 1:
  78.         execCommand.paraMiko(self)
  79.        
  80.          elif self._Choice == 2:
  81.         execCommand.SFTP(self)
  82.  
  83. # System Exit exits the script
  84.          else:
  85.         paramiko.SFTPClient().close()
  86.         paramiko.SSHClient().close()
  87.         raise SystemExit
  88.            
  89.          except Exception, e:
  90.                  print e
  91.  
  92.     def paraMiko(self):
  93.    
  94.     # Save time by defining the paramiko client. Set logging file local host side.
  95.     # Append host keys to known_host file using paramikos auto add policy.
  96.     # Connect to the host using the specified global class variables.
  97.     # If system allows it, call for a pseudo terminal. Grab banner from the server.
  98.     # Start bash string with a parenthases. Start the loop function.
  99.     # Setting a timeout of 2 seconds to allow buffer to fill (Banner grab)
  100.            
  101.     try:
  102.  
  103.             self.ssh = paramiko.SSHClient()
  104.         paramiko.util.log_to_file('/tmp/parakito.log')
  105.         self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  106.         self.ssh.connect(execCommand._host, execCommand._port, username=execCommand._uname,
  107. password=execCommand._passwd, timeout=2)
  108.         self._Chan = self.ssh.invoke_shell()
  109.         print ('\n[+] Connected\n')
  110.  
  111.         self._Data = self._Chan.recv(2014)
  112.         print '[+] Host Message Of The Day\n' + str(self._Data)
  113.  
  114.         self._Str += '('
  115.         execCommand.loop(self)
  116.  
  117.  
  118.     except Exception, e:
  119.             print e
  120.     finally:
  121.         self.ssh.close()
  122.        
  123.     def loop(self):
  124.    
  125.     # Question loop starts here, within its own function.
  126.  
  127.         try:
  128.             self._UI = raw_input("SSH >  ")
  129.             execCommand.Verify(self)
  130.  
  131.         except ValueError:
  132.             print("Apologies, I Wasnt Expecting That. Try Again...")
  133.             execCommand.loop(self)
  134.  
  135.     def Verify(self):
  136.  
  137.     # This function loops the question, adding each input to the string (self._str)
  138.     # If Disconnect is present in the return, we print the concatenated string output
  139.     # It then asks us if we are ready to proceed, if so it will execute the bash string
  140.     # To the server. '> /home/notalog.txt' is a way of saying, save all output to this file.
  141.    
  142.     try:  
  143.         if self._UI == str('Disconnect'):
  144.                
  145.          self._Str += 'uptime) > /home/notalog.txt'
  146.          print('\n\n'+self._Str)
  147.              
  148.                  self._Req = raw_input('\n[!] Fingers Trembling, Ready To Send? [Execute/Stop]: ')
  149.                  if self._Req == str("Execute"):
  150.                      print('\n[+] Issuing Commands To Server..\n')
  151.                          execCommand.Push(self)
  152.                  else:
  153.                          execCommand.loop(self)
  154.             else:
  155.          
  156.         self._Str += str((self._UI))+ '; '
  157.         execCommand.loop(self)
  158.                      
  159.    
  160.     except Exception, e:
  161.         print e
  162.              
  163.     def Push(self):
  164.  
  165.     # Standard (input, output, error) are declared as result of the execute command function
  166.     # In paramiko. Executing the class variable self._Str as the command to be executed.
  167.     # Wait for user input, then go to main menu.
  168.  
  169.         try:
  170.        
  171.         self._stdin, self._stdout, self._stderr = self.ssh.exec_command(self._Str)
  172.             raw_input('\nShall We Proceed?..')
  173.         execCommand()
  174.    
  175.                      
  176.       except Exception, e:
  177.             print e
  178.             self.ssh.close()
  179.  
  180.    
  181.    
  182.    
  183.     def SFTP(self):
  184.  
  185.     # Using the transport function from paramiko using the global class variables host, port
  186.     # Connecting using the global class variables uname and password
  187.    
  188.     # Setting the local and remote paths. SFTP.get takes two arguments, a send and a receive
  189.     # This sequence can be reversed when using the SFTP.put method to upload a file instead of download.
  190.     # The prog bar calculates transfer time and displays this in the interpreter
  191.  
  192.     def progBar(transferred, toBeTransferred):
  193.         print("\n[+] Transferred: {0}\tOut Of: {1}".format(transferred, toBeTransferred))
  194.    
  195.     try:
  196.          
  197.         self._T = paramiko.Transport((execCommand._host, execCommand._port))       
  198.         self._T.connect(username=execCommand._uname, password = execCommand._passwd)
  199.         self._SFTP = paramiko.SFTPClient.from_transport(self._T)
  200.  
  201.         self._remotepath='/home/notalog.txt'
  202.         self._localpath='/home/Spawn/Desktop/SFTP/notalog.txt'
  203.        
  204.            
  205.         self._SFTP.get(self._remotepath,self._localpath, callback=progBar)
  206.         print('\n[+] File Successfully Sent')
  207.         raw_input("\n[!] Ready To Proceed?")
  208.         self._SFTP.close()
  209.         startUP()
  210.  
  211.     except Exception, e:
  212.         print e
  213.  
  214. try:
  215.     # Classes are initialised by defining their name within a function
  216.  
  217.     s = startUP()
  218.  
  219. except KeyboardInterrupt:
  220.  
  221.     # Keyboard interrupt; Control - C.
  222.     # Using the time module to implement delays in messages
  223.     # Raw input at the end waiting for enter press
  224.  
  225.     paramiko.SSHClient().close()       
  226.     print('\n\n[+] Connection Terminated By User, Closing SSH Connection..')
  227.     time.sleep(0.5)    
  228.     print('\n[+] SSH Connection Terminated Successfully..')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement