Beispiel #1
0
 def __init__(self, user=None, password=None, host=None, logfile=None, environment=None, verbose=False,
              virtualenv=None, working_dir=None):
     """
     :param user: the remote user account
     :type user: str
     :param password: the password for the remote user account
     :type password: str
     :param host: the remote machine
     :type host: str
     :param logfile: optional logfile
     :type logfile: str
     :param environment: Optional key to Project.prefix and Project.postfix dictionaries
     :type environment: str
     :param verbose: extra logging
     :type verbose: bool
     :param virtualenv: directory that contains a virtual environment to activate upon connection
     :type virtualenv: str
     """
     super(RemoteShell, self).__init__(is_remote=True, verbose=verbose)
     if not user:
         user = Project.user
     if not host:
         host = Project.address
     Project.user = user
     Project.password = password
     Project.address = host
     self.ssh = pxssh(timeout=1200)
     try:
         if password:
             self.ssh.login(host, user, password)
         else:
             self.ssh.login(host, user)
     except ExceptionPxssh:
         if not password:
             password = Project.password
         if not password:
             password = getpass('password for {user}@{host}: '.format(user=user, host=host))
         self.ssh.close()
         self.ssh = pxssh(timeout=1200)
         self.ssh.login(host, user, password)
     self.accept_defaults = False
     self.logfile = logfile
     self.prefix = []
     self.postfix = []
     if environment:
         self.prefix.extend(Project.prefix[environment] or [])
         self.postfix.extend(Project.postfix[environment] or [])
     if working_dir:
         self.prefix.insert(0, "cd {dir} ; ".format(dir=working_dir))
     if virtualenv:
         self.prefix.insert(0, "source {path}/bin/activate ; ".format(path=virtualenv))
     if verbose:
         info("remote: {user}@{host}".format(user=user or "", host=host or ""))
 def __init__(self, host, user, password, debug=False):
     self.host = host
     self.user = user
     self.password = password
     self.plex_version = "0"
     self.plex_installed = False
     if debug:
         self.ssh = pxssh.pxssh(logfile=sys.stdout)
     else:
         self.ssh = pxssh.pxssh()
     
     self.login()
Beispiel #3
0
def connect():
    global args

    if (args.method == "ssh"):
        #spawncmd = 'ssh ' + args.user + '@' + args.switch
        spawncmd = 'ssh -l ' + args.user + ' ' + args.switch
    else:
        spawncmd = 'telnet ' + args.switch
    print (spawncmd)

    try:
        #conn = pexpect.spawn(args.method, [args.user, '@', args.switch])
        #conn = pexpect.spawn(spawncmd)
        s = pxssh.pxssh()
        s.login(args.switch, args.user, args.passwd)
        #conn = pexpect.spawn('ssh [email protected]')
    except Exception as err:
        print ("Unexpected error: ", sys.exc_info()[0], type(err), err.args, err)
        sys.exit(0)

    pdb.set_trace()
    s.sendline('uptime')
    s.prompt()
    s.logout()
    sys.exit(0)
Beispiel #4
0
	def connect(self):
		data = self.config
		unconnected = True
		tries = 0
		while unconnected and tries <= self.max_tries:
			if tries == self.max_tries:
				self.warn("Maximum allowed tries are about to get over!")

			try:
				session = pxssh.pxssh()
				self.info("Logging into " + data['hostname'] + "...")
				if not session.login (data['hostname'], data['username'], data['password']):
					self.error("SSH login failed.")
					print str(session)
					print
					self.warn("Unable to connect. Retrying...")
					tries = tries + 1
				else:
					self.info("Connected via SSH.")
					unconnected = False
					#return session
					self.session = session
			except Exception:
				self.warn("Unable to connect. Retrying...")
				tries = tries + 1
				unconnected = True
Beispiel #5
0
def application():
    #Credentials
    host = ""
    username = ""
    password = ""
    auth_number = "+44"
    auth_token = ""
    validator = RequestValidator(auth_token)
    url = ""
    sa = pxssh.pxssh()
    body_message = str(request.values.get('Body', None))
    signature = request.headers.get('X-Twilio-Signature')


    from_number = request.values.get('From', None)
    body1 = body_message.split(' ')[0]
    if (from_number == auth_number and body1 == "service"):
        sa.login(host, username, password)
        sa.sendline(body_message)
        sa.prompt()
        sa.logout()
        sms_content = "Done!"
        message = str(sms_content)
        resp = twilio.twiml.Response()
        resp.message(message)
        return str(resp)
    
    else:
        sms_content = "You are not allowed to send commands to this server"
        message = str(sms_content)
        resp = twilio.twiml.Response()
        resp.message(message)
        return str(resp)
        pass
Beispiel #6
0
def connect(host,user,password):
    try:
        session = pxssh.pxssh()
        session.login(host,user,password)
        print('[+]Password Found:'+password)
    except Exception,e:
        print ('[-] Error Connecting:'+str(e))
Beispiel #7
0
def go1(username, password):
	s = pxssh.pxssh()
	if not s.login ('cory.eecs.berkeley.edu', username, password):
	    print ("SSH session failed on login.")
	else:
	    print ("SSH session login successful")
	   
	    commands = ["glookup -t", "glookup", "glookup -s Total"]
	    ret = ""
	   
	    for tmp in commands:
	    	print(tmp)
	    	s.sendline(tmp)
	    	s.prompt()
	    	
	    	str = s.before
	    	str = str.decode()
	    	ret += str
	    
	    ret = ret.replace('glookup -t','')
	    ret = ret.replace('glookup -s Total','')
	    ret = ret.replace('glookup','')
	    
	    ret = ret.replace('\\r\\n','\n')
	  
	    text_file = open("output.txt","w")
	    text_file.write(ret)
	    text_file.close()

	    s.logout()
	    return None
def connectSSH(host, user, passwd):
    try:
        ssh = pxssh.pxssh()
        ssh.login(host, user, passwd, auto_prompt_reset=False)
        return ssh
    except Exception, e:
        print "%s is not vul" % host
    def _get_arp_data(self):
        """Open connection to the router and get arp entries."""
        from pexpect import pxssh
        import re

        try:
            cisco_ssh = pxssh.pxssh()
            cisco_ssh.login(self.host, self.username, self.password,
                            port=self.port, auto_prompt_reset=False)

            # Find the hostname
            initial_line = cisco_ssh.before.decode('utf-8').splitlines()
            router_hostname = initial_line[len(initial_line) - 1]
            router_hostname += "#"
            # Set the discovered hostname as prompt
            regex_expression = ('(?i)^%s' % router_hostname).encode()
            cisco_ssh.PROMPT = re.compile(regex_expression, re.MULTILINE)
            # Allow full arp table to print at once
            cisco_ssh.sendline("terminal length 0")
            cisco_ssh.prompt(1)

            cisco_ssh.sendline("show ip arp")
            cisco_ssh.prompt(1)

            devices_result = cisco_ssh.before

            return devices_result.decode('utf-8')
        except pxssh.ExceptionPxssh as px_e:
            _LOGGER.error("pxssh failed on login")
            _LOGGER.error(px_e)

        return None
Beispiel #10
0
def ssh_get_shell(host, username, password=None, keyfile=None, port=None, timeout=10, telnet=False, original_prompt=None):
    _check_env()
    start_time = time.time()
    extra_login_args = {}
    while True:
        if telnet:
            if keyfile:
                raise ValueError('keyfile may not be used with a telnet connection.')
            conn = TelnetConnection()
            if original_prompt:
                extra_login_args['original_prompt'] = original_prompt
            if port is None:
                port = 23
        else:  # ssh
            conn = pxssh.pxssh()

        try:
            if keyfile:
                conn.login(host, username, ssh_key=keyfile, port=port, login_timeout=timeout, **extra_login_args)
            else:
                conn.login(host, username, password, port=port, login_timeout=timeout, **extra_login_args)
            break
        except EOF:
            timeout -= time.time() - start_time
            if timeout <= 0:
                message = 'Could not connect to {}; is the host name correct?'
                raise DeviceError(message.format(host))
            time.sleep(5)

    conn.setwinsize(500,200)
    conn.sendline('')
    conn.prompt()
    conn.setecho(False)
    return conn
Beispiel #11
0
 def test_ssh_config_passing_string(self):
     ssh = pxssh.pxssh(debug_command_string=True)
     temp_file = tempfile.NamedTemporaryFile()
     config_path = temp_file.name
     string = ssh.login('server', 'me', password='******', spawn_local_ssh=False, ssh_config=config_path)
     if not '-F '+config_path in string:
         assert False, 'String generated from SSH config passing is incorrect.'
Beispiel #12
0
 def test_fake_ssh(self):
     ssh = pxssh.pxssh()
     ssh.login('server', 'me', password='******')
     ssh.sendline('ping')
     ssh.expect('pong', timeout=10)
     assert ssh.prompt(timeout=10)
     ssh.logout()
Beispiel #13
0
def test_linux():
    '''
    Verify logging into IOS XR Linux.
    Verify user is 'vagrant'.
    Verify can ping 'google.com'.
    Verify resolv.conf is populated.
    '''
    logger.debug('Testing XR Linux...')
    logger.debug('Connecting to port %s' % linux_port)

    try:
        s = pxssh.pxssh(options={
            "StrictHostKeyChecking": "no",
            "UserKnownHostsFile": "/dev/null"})
        s.login(hostname, username, password, terminal_type, linux_prompt, login_timeout, linux_port, auto_prompt_reset=False)

        s.prompt()
        logger.debug('Successfully logged into XR Linux')

        logger.debug('Check user:'******'whoami')
        output = s.expect(['vagrant', pexpect.EOF, pexpect.TIMEOUT])
        if not check_result(output, 'Correct user found'):
            return False
        s.prompt()

        logger.debug('Check pinging the internet:')
        s.sendline("ping -c 4 google.com | grep '64 bytes' | wc -l")
        output = s.expect(['4', pexpect.EOF, pexpect.TIMEOUT])
        if not check_result(output, 'Successfully pinged'):
            return False
        s.prompt()

        logger.debug('Check resolv.conf is correctly populated:')
        s.sendline("cat /etc/resolv.conf | grep 220")
        output = s.expect(['nameserver 208.67.220.220', pexpect.EOF, pexpect.TIMEOUT])
        if not check_result(output, 'nameserver 208.67.220.220 is successfully populated'):
            return False
        s.prompt()

        s.sendline("cat /etc/resolv.conf | grep 222")
        output = s.expect(['nameserver 208.67.222.222', pexpect.EOF, pexpect.TIMEOUT])
        if not check_result(output, 'nameserver 208.67.222.222 is successfully populated'):
            return False
        s.prompt()

        logger.debug('Check vagrant public key has been replaced by private:')
        s.sendline('grep "public" ~/.ssh/authorized_keys -c')
        output = s.expect(['0', pexpect.EOF, pexpect.TIMEOUT])
        if not check_result(output, 'SSH public key successfully replaced'):
            return False
        s.prompt()
        s.logout()
    except pxssh.ExceptionPxssh as e:
        logger.error("pxssh failed on login.")
        logger.error(e)
        return False
    else:
        logger.debug("Vagrant SSH to XR Linux is sane")
        return True
Beispiel #14
0
def __update_with_call_load(appName, creds):
    ''' Private method to run in a separate thread for each application/vm that must be updated with session load/call load. '''
    global callLoadDict
    sshHandle = pxssh.pxssh(options={"StrictHostKeyChecking": "no", "UserKnownHostsFile":"/dev/null"})   
    try:
        if sshHandle.login(creds['ip'], creds['username'], creds['password']):
            while threadsRunning.is_set():
                sshHandle.sendline(creds['command_to_send'])
                sshHandle.prompt()
                tempLines = sshHandle.before.decode('utf-8').splitlines()[-1]
                try:
                    tempCallLoadDict = json.loads(tempLines) if tempLines is not None else {}
                except ValueError:
                    log.warning("Invalid call info received, error in output of %s:%s. Provided output:\n\t%s " %(creds['ip'], creds['command_to_send'], tempLines))
                    tempCallLoadDict = {}
                tempCallLoadDict = {appName+'-'+k:v for k, v in tempCallLoadDict.items()}
                for aVm in tempCallLoadDict:
                    if aVm not in callLoadDict: callLoadDict[aVm] = {}                    
                    callLoadDict[aVm]['calls'] = tempCallLoadDict[aVm]
                #Ugly fix for confirming evacuation is 'actually' complete. Sorry. :(
                if mlp.evacuatingVm !='' and mlp.evacuatingVm in tempCallLoadDict and tempCallLoadDict[mlp.evacuatingVm]>0:
                    frontEndEventStack.append('Server-response: VM is operational. Evacuation complete'+'#{"evacuation":"stop"}')
                    mlp.evacuatingVm = ''
                time.sleep(fetchInterval)
            sshHandle.logout()
    except IndexError:
        log.error('"IndexError" while updating with call info. Porbable cause : Error in communication with %s' %(creds['ip']))
        return
    except pexpectEndOfFile:
        log.critical('pexpect: end-of-file exception; Failed to read call information. Failed to log in to %s. Running GUI without call-info. Restart program if necessary.' %(creds['ip']))
Beispiel #15
0
def main(run):

	try:
		printAlert(0,"Testing Mysql protocol [3306]")
		MySQLdb.connect(init.var['target'],init.var['user'],init.var['pass'],'')
		printAlert(3,"Logged with "+init.var['user']+"/"+init.var['pass']+" in Mysql")
	except:printAlert(1,"Service Off or No Logged.")

	try:
		printAlert(0,"Testing SSH protocol [22]")
		connect = pxssh.pxssh()
		connect.login(init.var['target'],init.var['user'],init.var['pass'])
		printAlert(3,"Logged with "+init.var['user']+"/"+init.var['pass']+" in SSH")
	except:printAlert(1,"Service Off or No Logged.")

	try:
		printAlert(0,"Testing FTP protocol [21]")
		ftp.login(init.var['user'],init.var['pass'])
		printAlert(3,"Logged with "+init.var['user']+"/"+init.var['pass']+" in FTP")
	except:printAlert(1,"Service Off or No Logged.")

	try:
		printAlert(0,"Testing POP3 protocol [110]")
		red=poplib.POP3(init.var['target'], 110)
		red.user(init.var['user']+"@"+init.var['target'])
		red.pass_(init.var['pass'])
		printAlert(3,"Logged with "+init.var['user']+"/"+init.var['pass']+" in POP3")
	except:printAlert(1,"Service Off or No Logged.")
	Space()
Beispiel #16
0
 def remote(self):
     """
     Create pxssh session and execute the command based on the type
     i.e. interactive single, interactive all or non-interactive
     """
     try:
         logger.info("remote")
         s = pxssh.pxssh(self.timeout)
         hostname = self.host
         username = self.username
         password = self.password
         s.login(hostname, username, password)
         if not interactive and args.command != "all":
             self.exec_remote_noninteractive(s=s)
         elif args.command != "all":
             self.exec_remote(s=s)
         else:
             self.exec_remote_all(s=s)
         s.logout()
     except pxssh.ExceptionPxssh as e:
         logger.error("ssh failed on login.")
     except pexpect.exceptions.TIMEOUT as e:
         logger.error("request timed out")
     except Exception as e:
         logger.error(str(e))
def connect(host, user, password, release):
	# Grab global variables
	global Found
	global Fails
	global EOF_Fails
	global DEBUG_MODE
	global TIMEOUT
	global MAX_ERRORS

	if DEBUG_MODE: print "[DEBUG] Connect() password variable: " + password

	# Test connection via SSH
	try:
		s = pxssh.pxssh()
		s.login(host, user, password, login_timeout=TIMEOUT, quiet=False)
		print "[+] *** Password Found: " + password
		FoundPassASCII_Art(password)
		Found = True

	# Handle thrown back errors
	except Exception, e:

		##print "[DEBUG] Exception: " + str(e)

		if DEBUG_MODE:
			if 'password refused' in str(e):
				print "[DEBUG] password refused exception."
			elif 'permission denied' in str(e):
				print "[DEBUG] permission denied exception. Wrong password"
			if EOF_Fails > MAX_ERRORS:
				print "[DEBUG] EOF error details: " + str(e)
		# Timeout error
		if 'read_nonblocking' in str(e):
			if DEBUG_MODE: print "error recieved: " +str(e)
			Fails += 1
			time.sleep(5)
			connect(host, user, password, False) # We only want the original caller to release the lock. The children should not be able to release the lock.

		# Too many connections. Slow down
		elif 'synchronize with original prompt' in str(e):
			if DEBUG_MODE: print "error recieved: " +str(e)
			time.sleep(1)
			connect(host, user, password, False) # We only want the original caller to release the lock.

		# Connection is refused by server
		elif "Connection refused" in str(e):
			print "[-] Connection refused by host"
			print "[-] Host probably does not have SSH enabled."
			Fails = MAX_ERRORS + 1

		# If host is using a different SSH key than the one you have saved.
		elif 'Host key verification failed' in str(e):
			print "[!] Host key verification failed!" +\
			" Possible MITM attack. Check your known SSH keys file."
			Fails = MAX_ERRORS + 1

		# Generic error usually recieved from pxssh.
		elif 'EOF' in str(e):
			print "[-] Got back a generic error..."
			EOF_Fails += 1
Beispiel #18
0
    def ssh_connection(self):
        """Retrieve data from ASUSWRT via the ssh protocol."""
        from pexpect import pxssh, exceptions

        ssh = pxssh.pxssh()
        try:
            ssh.login(self.host, self.username, **self.ssh_secret)
        except exceptions.EOF as err:
            _LOGGER.error("Connection refused. Is SSH enabled?")
            return None
        except pxssh.ExceptionPxssh as err:
            _LOGGER.error("Unable to connect via SSH: %s", str(err))
            return None

        try:
            ssh.sendline(_IP_NEIGH_CMD)
            ssh.prompt()
            neighbors = ssh.before.split(b"\n")[1:-1]
            if self.mode == "ap":
                ssh.sendline(_ARP_CMD)
                ssh.prompt()
                arp_result = ssh.before.split(b"\n")[1:-1]
                ssh.sendline(_WL_CMD)
                ssh.prompt()
                leases_result = ssh.before.split(b"\n")[1:-1]
            else:
                arp_result = [""]
                ssh.sendline(_LEASES_CMD)
                ssh.prompt()
                leases_result = ssh.before.split(b"\n")[1:-1]
            ssh.logout()
            return AsusWrtResult(neighbors, leases_result, arp_result)
        except pxssh.ExceptionPxssh as exc:
            _LOGGER.error("Unexpected response from router: %s", exc)
            return None
Beispiel #19
0
def single_gameserver(num, hostname, passwd):

    try:
#        cmd = '''\
#                mysql -uroot -S /tmp/mysqlzz{0}.sock -e "show databases;" > /dev/null 2>&1;[ $(echo $?) == 0 ] && \
#                mysql -uroot -S /tmp/mysqlzz{0}.sock -e "show slave status\G" | grep "Running" | sed "s/^ *//" || \
#                mysql -uroot -S /tmp/mysqlzz{0}.sock -p{1} -e "show slave status\G" | grep "Running" | sed "s/^ *//"
#              '''.format(num, passwd)
        if passwd == 'Null':
            cmd = '''mysql -uroot -S /tmp/mysqlzz{0}.sock -e "show slave status\G" | grep "Running" | sed "s/^ *//"'''.format(num)
        else:
            cmd = '''mysql -uroot -S /tmp/mysqlzz{0}.sock -p{1} -e "show slave status\G" | grep "Running" | sed "s/^ *//"'''.format(num, passwd)

#        print num
#        print hostname
#        print passwd
#        print cmd
        s = pxssh.pxssh()
        s.login(hostname, username, password, port=2009, login_timeout=600)
        s.sendline(cmd)
        s.prompt(timeout=600)
        output = s.before.split('\r\n')
        print output
        s.logout()
    except pxssh.ExceptionPxssh as e:
        print 'pxssh failed on login.'
        print e
Beispiel #20
0
def pxssh_connect(host, user, password, release):
    global gHackedHostList
    Found = False
    try:
        session = pxssh.pxssh()
        session.login(host, user, password)
        session.expect([pexpect.EOF, pexpect.TIMEOUT])
        LoginInfo = '{0}: {1}/{2}'.format(host, user, password)
        gHackedHostList.append(LoginInfo)
        print '[+] Password found on ' + LoginInfo
        Found = True
    except Exception, e:
        if 'read_nonblocking' in str(e):
            sys.stdout.write('read_nonblocking encountered, another try\n')
            sys.stdout.flush()
            time.sleep(5)
            connect(host, user, password, False)
        elif 'synchronize with original prompt' in str(e):
            sys.stdout.write('synchronize with orignal prompt, another try\n')
            sys.stdout.flush()
            time.sleep(1)
            connect(host, user, password, False)
        else:
            sys.stderr.write('[-] Exception: ' + str(e) + '\n')
            sys.stderr.flush()
Beispiel #21
0
    def __init__(self):

        """
        The constructor ...
        :return:
        """

        # Call the constructor of the base class
        super(Remote, self).__init__()

        # -- Attributes --

        # The SSH interface, an instance of the pxssh class
        self.ssh = pxssh.pxssh()

        # The host instance
        self.host = None

        # The VPN service
        self.vpn = None

        # A flag indicating whether the connection with the remote has been established
        self.connected = False

        # A regular expression object that strips away special unicode characters, used on the remote console output
        self.ansi_escape = re.compile(r'\x1b[^m]*m')

        # Flag that says whether we are in a remote python session
        self.in_python_session = False

        # Temp directory will be set in setup
        self._temp_path = None

        # Flag that says whether we have created a temporary directory
        self._temp_dir_created = False
Beispiel #22
0
def setConfigIPToActiveCIC():
    '''
    Method that checks if the CIC IP provided in the config.json file is the main CIC. If not, fetches the main CIC IP and updates the config.json file accordingly.
    If this crashes, the config.json file may end up being blank, replace it with a backup copy in such cases. (There is one on the 'dummy_inputs' directory) 
    '''
    ps, ps1 = (pxssh.pxssh(options={"StrictHostKeyChecking": "no", "UserKnownHostsFile":"/dev/null"}),)*2 
    with open('config.json', 'r') as conF:
        configDict = json.loads(conF.read())
        ip, user, pw = configDict['ssh']['ip'], configDict['ssh']['username'], configDict['ssh']['password']
    if ps.login(ip, user, pw):
        current_cic_hostname = "".join(execute_commands(ps, ['hostname -s'])[-1].split())+'.domain.tld'
        main_cic_hostname = execute_commands(ps, ['echo $(sudo crm_mon -1 | grep cmha| grep Started)'])[0].rsplit('Started')[-1]
        main_cic_hostname = "".join(main_cic_hostname.split())
        log.info('Main cic hostname: "%s"' %(main_cic_hostname))
        log.debug('Current cic hostname: "%s"' %(current_cic_hostname))
        if current_cic_hostname!=main_cic_hostname:
            log.info('Currently set IP in the \'config.json\' file does not belong to the main CIC, fetching main cic IP for GUI-config file. This might take upto 1 minute.')            
            main_cic_ip_string = execute_commands(ps, ['ssh '+user+'@'+main_cic_hostname, pw ,'echo $(ifconfig br-ex | grep "inet addr:")'])[-2]
            log.debug('main cic ip string %s' %(main_cic_ip_string))
            execute_commands(ps, ['exit'])
            main_cic_ip_string = ["".join(s.split()) for s in re.findall(r'(?<=inet addr:)(.+)(?=Bcast)', main_cic_ip_string)][0]
            log.info('Main cic IP: %s' %(main_cic_ip_string))
            configDict['ssh']['ip'] = main_cic_ip_string
            with open('config.json', 'w') as conF:
                conF.write(json.dumps(configDict, indent=4, separators=(',', ':'), sort_keys=True))
        else:
            log.info("Config file has the main CIC IP.")
            ps.logout()
Beispiel #23
0
 def ssh_connection(self):
     """Retrieve data from ASUSWRT via the ssh protocol."""
     from pexpect import pxssh
     try:
         ssh = pxssh.pxssh()
         ssh.login(self.host, self.username, self.password)
         ssh.sendline(_IP_NEIGH_CMD)
         ssh.prompt()
         neighbors = ssh.before.split(b'\n')[1:-1]
         if self.mode == 'ap':
             ssh.sendline(_ARP_CMD)
             ssh.prompt()
             arp_result = ssh.before.split(b'\n')[1:-1]
             ssh.sendline(_WL_CMD)
             ssh.prompt()
             leases_result = ssh.before.split(b'\n')[1:-1]
         else:
             arp_result = ['']
             ssh.sendline(_LEASES_CMD)
             ssh.prompt()
             leases_result = ssh.before.split(b'\n')[1:-1]
         ssh.logout()
         return (neighbors, leases_result, arp_result)
     except pxssh.ExceptionPxssh as exc:
         _LOGGER.exception('Unexpected response from router: %s', exc)
         return ('', '', '')
 def invade(self, clientInfo):
     if clientInfo is not None:
         try:
             print "starting ssh..."
             ssh = pxssh.pxssh()
             #ssh.PROMPT= 'SSH> '
             #options={"StrictHostKeyChecking": "no", "UserKnownHostsFile": "/dev/null"})
             hostname = clientInfo[IPADDR].strip()
             username = clientInfo[USER].strip()
             password = clientInfo[PASSWORD].strip()
             destDir  = clientInfo[DIR].strip()
             dloadUrl = clientInfo[URL].strip()
             if hostname in REMOTE_CLIENTS_EVENTS.keys():
                 if REMOTE_CLIENTS_EVENTS[hostname] is "Installing":
                     print "prevented duplicate install"
                     return
                 cid = ThinClient.ComputeClientID(hostname)
                 if cid in KNOWN_CLIENTS.keys():
                     if KNOWN_CLIENTS[cid].progress() > 0 and KNOWN_CLIENTS[cid].progress() < 100 and KNOWN_CLIENTS[cid].isZombie() == False:
                         print "prevented duplicate install"
                         return
             reset = clientInfo[RESET].strip() == "reset"
             REMOTE_CLIENTS_EVENTS[hostname] = "Installing"
             ssh.login(hostname, username, password)
             print ssh.before
             ssh.sendline("export DISPLAY=:0")   # cd to directory where you want to install
             ssh.prompt()             # match the prompt
             ssh.sendline("mkdir -p " + destDir)   # cd to directory where you want to install
             ssh.prompt()             # match the prompt
             ssh.sendline("cd " + destDir)   # cd to directory where you want to install
             ssh.prompt()             # match the prompt
             ssh.sendline("rm -rf agent agent.tgz")   # Remove the old install
             print ssh.before
             ssh.prompt()
              # match the prompt
             ssh.sendline('curl -k -o client.tgz ' + dloadUrl)
             print ssh.before
             ssh.prompt()
             ssh.sendline('tar zxf client.tgz') # unzip the package
             print ssh.before
             ssh.prompt()
             url = 'http://' + self.address + ':' + serverGlobalConfig['port']
             if (reset == True):
                 cmd = 'setsid python agent/AutomationAgent.py server ' + url + ' --debug >'+ os.path.join(destDir, 'automation-console.log') +' 2>&1 &'
                 clientInfo[RESET] = "noreset"
             else:
                 cmd = 'setsid python agent/AutomationAgent.py server ' + url + ' --debug --noreset >'+ os.path.join(destDir, 'automation-console.log') +' 2>&1 &'
             print cmd
             ssh.sendline(cmd)
             ssh.prompt()
             #ssh.sendline("sleep 2")
             #ssh.prompt()
             ssh.logout()
             cid = ThinClient.ComputeClientID(hostname)
             REMOTE_CLIENTS[cid] = (hostname, ' '.join(clientInfo))
             REMOTE_CLIENTS_EVENTS[hostname] = "Installed"
         except Exception as e:
             print "Remote install failed for :",' '.join(clientInfo)
             REMOTE_CLIENTS_EVENTS[hostname] = "Install Failed"
Beispiel #25
0
 def test_fake_ssh(self):
     ssh = pxssh.pxssh()
     # ssh.logfile_read = sys.stdout  # DEBUG
     ssh.login("server", "me", password="******")
     ssh.sendline("ping")
     ssh.expect("pong", timeout=10)
     assert ssh.prompt(timeout=10)
     ssh.logout()
	def __init__(self, hostname='127.0.0.1', port=22, username='******', password='', options={"StrictHostKeyChecking":"no"}, add_options={}):
		self.s = s = pxssh.pxssh()
		options.update(add_options)
		s.options = options
		print "Connecting via SSH to %s@%s" % (username,hostname)
		if not s.login(server=hostname, username=username, password=password, port=port):
			raise RuntimeError("Invalid SSH connection or credentials")
		print "Successfully connected via SSH"
Beispiel #27
0
 def connect(self):
     try:
         s = pxssh()
         s.login(self.host, self.user, self.password)
         return s
     except Exception, e:
         print e
         print "[ - ] Error Connecting"
Beispiel #28
0
 def test_wrong_pw(self):
     ssh = pxssh.pxssh()
     try:
         ssh.login("server", "me", password="******")
     except pxssh.ExceptionPxssh:
         pass
     else:
         assert False, "Password should have been refused"
Beispiel #29
0
 def test_wrong_pw(self):
     ssh = pxssh.pxssh()
     try:
         ssh.login('server', 'me', password='******')
     except pxssh.ExceptionPxssh:
         pass
     else:
         assert False, 'Password should have been refused'
Beispiel #30
0
 def test_connection_refused(self):
     ssh = pxssh.pxssh()
     try:
         ssh.login('noserver', 'me', password='******')
     except pxssh.ExceptionPxssh:
         pass
     else:
         assert False, 'should have raised exception, pxssh.ExceptionPxssh'
 def run(self):
     time.sleep(5)
     start = time.time()
     self.lnk = pxssh.pxssh()
     hostname = '10.212.212.49'
     username = '******'
     password = '******'
     self.lnk.login(hostname, username, password)
     end = time.time()
     print('Vacuum RPi connected. Time elapsed: ' +
           str('%.2f' % (end - start)) + " seconds")
     self.lnk.sendline("cd ~/Desktop/vacuum_controller2")
     self.lnk.sendline("python")
     self.lnk.sendline("import vacuum_control")
     self.lnk.sendline("tic = vacuum_control.TIC()")
     print("Vacuum RPi - connected to vacuum_control.py")
Beispiel #32
0
def connect(host, user, password, release):
    global Found
    global Fails
    try:
        s = pxssh.pxssh()
        s.login(host, user, password)
        print '[+] Password Found: ' + password
        Found = True
    except Exception, e:
        if 'read_nonblocking' in str(e):
            Fails += 1
            time.sleep(5)
            connect(host, user, password, False)
        elif 'synchronize with original prompt' in str(e):
            time.sleep(1)
            connect(host, user, password, False)
    def connectSSH(self):
        res = os.system('ping -c 1 ' + self.ipaddr)
        if res != 0:
            print 'Host is not reachable'
            return None

        cli = pxssh.pxssh()
        try:
            res = cli.login(self.ipaddr,
                            self.userid,
                            self.userpw,
                            login_timeout=30)
        except pxssh.ExceptionPxssh, e:
            print "LogIn Failed - [%s]" % str(e)

            return None
Beispiel #34
0
    def execute_ssh_execute_file(args):
        '''
		SSH directly into the machine using parameters received
		'''
        ip = args["IP"]
        user = args["User"]
        password = args["Pass"]

        try:
            print("File Being Executed")
            file_command = "{} {}".format("bash", "exe.sh")
            ssh_handle = pxssh.pxssh(options={
                "StrictHostKeyChecking": "no",
                "UserKnownHostsFile": "/dev/null"
            })
            ssh_handle.login(ip, user, password)
            index = ssh_handle.expect(['[#\$]', '$', pexpect.EOF])

            if index == 0:
                ssh_handle.sendline("yes")
                ssh_handle.sendline(password)
                ssh_handle.sendline('sudo -s')
                ssh_handle.sendline(password)
                ssh_handle.sendline(file_command)
                ssh_handle.expect("#")
                ssh_handle.sendline("exit")
                ssh_handle.expect("$")
                ssh_handle.logout()

                print("File Succesfully Executed")

            if index == 1:
                ssh_handle.sendline('sudo -s')
                ssh_handle.sendline(password)
                ssh_handle.sendline(file_command)
                ssh_handle.expect("#")
                ssh_handle.sendline("exit")
                ssh_handle.expect("$")
                ssh_handle.logout()

                print("File Succesfully Executed")

        except Exception as e:
            print(str(e))

        except pxssh.ExceptionPxssh as e:
            print(str(e))
	def Temp(self):
		print('Getting Temp Logs')
		self.lnk = pxssh.pxssh()
		self.lnk.login(self.TCS,self.username,self.password)
		self.lnk.sendline('cd ~/Desktop/FHiRE-TCS/')
		self.lnk.sendline('scp tempLog.dat [email protected]:/home/fhire/Desktop/FHiRE_GAM/logs')
		time.sleep(3)
		i = self.lnk.expect('[email protected]\'s password:'******'scp LPresistorsLog.dat [email protected]:/home/fhire/Desktop/FHiRE_GAM/logs')
		time.sleep(3)
		i = self.lnk.expect('[email protected]\'s password:'******'scp LPdiodesLog.dat [email protected]:/home/fhire/Desktop/FHiRE_GAM/logs')
		time.sleep(3)
		i = self.lnk.expect('[email protected]\'s password:'******'scp controlTemp.dat [email protected]:/home/fhire/Desktop/FHiRE_GAM/logs')
		time.sleep(3)
		i = self.lnk.expect('[email protected]\'s password:'******'scp monitoringTemp.dat [email protected]:/home/fhire/Desktop/FHiRE_GAM/logs')
		time.sleep(3)
		i = self.lnk.expect('[email protected]\'s password:'******'Temp Logs Obtained')
Beispiel #36
0
def ssh():
    start_time = time()
    value = 0
    recibido = 0
    enviado = 0
    conexiones = 0
    ssh_servidor = '10.0.0.19'
    ssh_usuario = 'daniela'
    ssh_clave = 'password'

    # Comandos que vamos a ejecutar en el servidor

    trafico_recibido = 'snmpget -v2c -c sshgroup localhost 1.3.6.1.2.1.4.3.0'
    trafico_enviado = 'snmpget -v2c -c sshgroup localhost 1.3.6.1.2.1.4.9.0'
    conexiones_establecidas = 'snmpget -v2c -c sshgroup localhost 1.3.6.1.2.1.6.9.0'
    len_comando = len(trafico_recibido)

    try:
        s = pxssh.pxssh()

        if not s.login(ssh_servidor, ssh_usuario, ssh_clave):
            value = 33

        else:
            value = 100

            s.sendline(trafico_recibido)
            s.prompt()  # match the prompt
            recibido = str(s.before)
            recibido = recibido[(len_comando + 39):(len(recibido) - 5)]

            s.sendline(trafico_enviado)
            s.prompt()  # match the prompt
            enviado = str(s.before)
            enviado = enviado[(len_comando + 39):(len(enviado) - 5)]

            s.sendline(conexiones_establecidas)
            s.prompt()  # match the prompt
            conexiones = str(s.before)
            conexiones = conexiones[(len_comando + 37):(len(conexiones) - 5)]

            s.logout()
    except:
        value = 33

    elapsed_time = time() - start_time
    return recibido, enviado, conexiones, value, elapsed_time
def distribute_publickey_to_hosts(source_host, dest_hosts_list, user,
                                  password):
    try:
        ssh_connection = pxssh.pxssh()
        ssh_connection.login(source_host, user, password)

        already_has_pubkey = run_command_and_return_status(
            ssh_connection, '[ -f ~/.ssh/id_rsa ]')
        if already_has_pubkey != 0:
            rc = run_command_and_return_status(
                ssh_connection, 'ssh-keygen -f ~/.ssh/id_rsa -t rsa -N ""')
            if rc > 0:
                ssh_connection.logout()
                return False

        for dest_host in dest_hosts_list:
            print("Distributing key from SERVER: " + source_host +
                  " to host: " + dest_host)

            ssh_connection.sendline(
                'ssh-copy-id -i ~/.ssh/id_rsa ' + dest_host +
                ' -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no')
            ssh_connection.prompt()
            prompt_message = ssh_connection.before
            print(prompt_message)
            if prompt_message.lower().find('password:'******'echo $?')
            ssh_connection.prompt()
            rc = int(ssh_connection.before.split('\n')[1])

            if rc != 0:
                raise Exception('Error while distributing key to host ' +
                                dest_host)

            print('Key distributed')

        ssh_connection.logout

    except Exception as e:
        print('ERROR: in function -> distribute_publickey_to_hosts')
        print(e)
        return False

    return True
Beispiel #38
0
def sshbrute(web):

    #print(R+'\n   ===============================')
    #print(R+'\n    S S H   B R U T E F O R C E R')
    #print(R+'   ——·‹›·––·‹›·——·‹›·——·‹›·——·‹›·–\n')
    from core.methods.print import pbrute
    pbrute("ssh")
             
    try:
        print(GR+' [*] Testing target...')
        ip = socket.gethostbyname(web)
        m = input(O+' [§] Use IP '+R+str(ip)+O+'? (y/n) :> ')
        if m == 'y' or m == 'Y':
            pass
        elif m == 'n' or m == 'N':
            ip = input(O+' [§] Enter IP :> ')

        print(G+' [+] Target appears online...')
        port = input(GR+' [§] Enter the port (eg. 22) :> ')

        try:
            with open('files/brute-db/ssh/ssh_defuser.lst','r') as users:
                for u in users:
                    u = u.strip('\n')
                    sshuser.append(u)

            with open('files/brute-db/ssh/ssh_defpass.lst','r') as pas:
                for p in pas:
                    p = p.strip('\n')
                    sshpass.append(p)
        except IOError:
            print(R+' [-] Importing wordlist failed!')

        for user in sshuser:
            for password in sshpass:
                try:
                    connect = pxssh.pxssh()
                    connect.login(ip,str(user),password)
                    if True:
                        print(G+' [!] Successful login with ' +O+user+G+ ' and ' +O+password)
                        break
                except:
                    print(C+' [!] Checking '+B+user+C+' and '+B+password+'...')

    except:
        print(R+' [-] Target seems to be down!')
    print(G+" [+] Done!")
Beispiel #39
0
    def test_custom_ssh_cmd_debug(self):
        ssh = pxssh.pxssh(debug_command_string=True)
        cipher_string = '-c aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,' \
            + 'aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,' \
            + 'aes256-cbc,arcfour'
        confirmation_strings = 0
        confirmation_array = [cipher_string, '-2']
        string = ssh.login('server',
                           'me',
                           password='******',
                           cmd='ssh ' + cipher_string + ' -2')
        for confirmation in confirmation_array:
            if confirmation in string:
                confirmation_strings += 1

        if confirmation_strings != len(confirmation_array):
            assert False, 'String generated for custom ssh client command is incorrect.'
Beispiel #40
0
 def login_test(self, host, user, password):
     targethost = host
     login_user = user
     login_pwd = password
     print targethost, login_user, login_pwd
     try:
         s = pxssh.pxssh()
         s.login(str(host), str(user), str(password), login_timeout=1)
         print "[+]succeed found %s---%s:%s" % (targethost, login_user,
                                                login_pwd)
         fs = open('result.txt', 'a+')
         fs.write("[+]succeed found %s---%s:%s" %
                  (targethost, login_user, login_pwd) + '\n')
         return False
     except:
         return True
         pass
Beispiel #41
0
def trySSH(hostname, username, password):
    try:
        conn = pxssh.pxssh()
        conn.login(hostname, username, password, auto_prompt_reset=False)
        print("SSH > Login no hostname " + hostname + " feito com sucesso")
        rootpassword = getpass.getpass('root password: ')
        conn.sendline("enable")
        print(conn)
        conn.prompt()
        conn.sendline(rootpassword)
        conn.logout()
        print("SSH > Root Acess")
        return True
    except Exception as e:
        print("SSH > Login no hostname " + hostname + " falhou")
        print(e)
        return False
Beispiel #42
0
def pxssh_ssh_tunneling_vnc(local_usocket_name, target_host, vnc_port,
                            ssh_port, ssh_login, ssh_password,
                            ssh_private_key_filename,
                            ssh_private_key_passphrase):
    """
    local_usocket_name :         must be absolute path
    target_host :                ssh and vnc host
    vnc_port :                   vnc port
    ssh_port :                   ssh port
    ssh_login :                  ssh login
    ssh_password :               ssh password
    ssh_private_key_filename :   ssh private key filename
    ssh_private_key_passphrase : ssh private key passphrase
    """
    from pexpect import pxssh
    p = None
    try:
        p = pxssh.pxssh(
            ignore_sighup=False,
            options={
                "StrictHostKeyChecking": "no",
                "UserKnownHostsFile": "/dev/null",
                "PubkeyAcceptedKeyTypes": "+ssh-dss"
            }
        )
        use_private_key = (
            bool(ssh_private_key_filename) and
            bool(ssh_private_key_passphrase)
        )
        if not use_private_key:
            p.force_password = True
        remove_file(local_usocket_name)
        p.login(
            server=target_host,
            username=ssh_login,
            ssh_key=ssh_private_key_filename if use_private_key else None,
            password=ssh_private_key_passphrase if use_private_key else ssh_password,
            port=ssh_port,
            ssh_tunnels={
                'local': [f'{local_usocket_name}:localhost:{vnc_port}']
            }
        )
    except Exception as e:
        Logger().info(f"Tunneling with PXSSH Error {e}")
        p = None
    return p
Beispiel #43
0
    def connect(self):
        """Connect to the ASUS-WRT SSH server."""
        from pexpect import pxssh

        self._ssh = pxssh.pxssh()
        if self._ssh_key:
            self._ssh.login(self._host,
                            self._username,
                            ssh_key=self._ssh_key,
                            port=self._port)
        else:
            self._ssh.login(self._host,
                            self._username,
                            password=self._password,
                            port=self._port)

        super(SshConnection, self).connect()
Beispiel #44
0
 def ssh_conn(self, hostname, username, password):
     try:
         print("Connecting to ", hostname)
         self.ssh = pxssh.pxssh()
         print(hostname, username, password)
         self.ssh.login(hostname,
                        username,
                        password,
                        original_prompt="[#>$]",
                        login_timeout=5000,
                        auto_prompt_reset=False)
         print("Connected")
     except pxssh.ExceptionPxssh as error:
         print("Login failed")
         print(str(error))
         self.ssh = False
     return self.ssh
Beispiel #45
0
def InstallApache(IP, username, password):
    session = pxssh.pxssh()
    session.login(IP, username, password)
    session.sendline('sudo apt update')
    session.prompt()
    session.sendline('Password01')
    print("Updated successfully")
    session.prompt()
    session.sendline('sudo apt-get -y install apache2')
    session.prompt()
    print("Installed Apache2 successfully")
    session.sendline('sudo systemctl start apache2')
    session.prompt()
    session.sendline('sudo systemctl enable apache2')
    session.prompt()
    print("Enabled Apache2 @boot successfully")
    session.logout()
Beispiel #46
0
    def spark_restart_shell(self):
        """
        stop_thrift = '/data01/spark/sbin/stop-thriftserver.sh'
        stop_all = '/data01/spark/sbin/stop-all.sh'
        start_all = '/data01/spark/sbin/start-all.sh'
        start_thrift = '/data01/spark/sbin/start-thriftserver.sh --master spark://21.2.2.58:7077 --total-executor-cores 32 --executor-memory 4g'
        """
        try:
            stop_thrift = self.spark_home + '/sbin/stop-thriftserver.sh'
            stop_all = self.spark_home + '/sbin/stop-all.sh'
            start_all = self.spark_home + '/sbin/start-all.sh'
            start_thrift = self.spark_home + '/sbin/start-thriftserver.sh --master spark://' + \
                           self.hive2_host + ':' + self.master_port + ' --total-executor-cores ' + \
                           self.total_exe_cores + ' --executor-memory ' + self.exe_memory

            s = pxssh.pxssh(timeout=self.restart_time_out)
            password = base64.decodestring(self.restart_password)
            s.login(self.restart_client_ip,
                    self.restart_user_name,
                    self.password,
                    original_prompt='[$#>]')
            # command1
            command1 = stop_thrift
            s.sendline(command1)
            s.prompt()
            print s.before
            # command2
            command2 = stop_all
            s.sendline(command2)
            s.prompt()
            print s.before
            # command3
            command3 = start_all
            s.sendline(command3)
            s.prompt()
            print s.before
            # command4
            command4 = start_thrift
            s.sendline(command4)
            s.prompt()
            print s.before
            s.logout()
            #
        except pxssh.ExceptionPxssh, e:
            print 'pxssh failed on login.'
            print str(e)
Beispiel #47
0
    def create_session(self):
        try:
            sesh = pxssh.pxssh(options={
                "StrictHostKeyChecking": "no",
                "UserKnownHostsFile": "/dev/null"
            })
            # Enable the following line if you need to see all output.
            # This will make Ansible think that there was an error, however.
            #sesh.logfile_read = sys.stdout
            if self.log:
                # To only capture output (and not passwords) change logfile to logfile_read
                sesh.logfile = file(self.log_file, 'w')
            sesh.force_password = True
            return sesh

        except (pxssh.ExceptionPxssh, pexpect.ExceptionPexpect) as e:
            self.module.fail_json(msg="Connection Error: {}".format(e))
Beispiel #48
0
def InstallMySQL(IP, username, password):
    session = pxssh.pxssh()
    session.login(IP, username, password)
    session.sendline('sudo apt update')  #very necessary!
    session.prompt()
    session.sendline('Password01')
    print("Updated successfully")
    session.prompt()
    session.sendline('sudo apt-get -y install mysql-client')
    session.prompt()
    session.sendline('sudo apt-get -y install mysql-server')
    session.promt()
    session.sendline('sudo systemctl start mysql')
    session.promt()
    session.sendline('sudo systemctl enable mysql')  #auto start @boot
    print("MySQL installed successfully")
    session.logout()
Beispiel #49
0
def AtaqueFuerzaBrutaSSH(Ipvictima,Usuariovictima):

    print("                                                                          ")
    print(colored("Para el ataque se usara el diccionario de password por defecto",'green',attrs=['bold']))
    print(colored("Diccionario de passwords: ",'green',attrs=['bold']),colored("FichEnt/diccionario.txt",'blue',attrs=['bold']))
    print("                                                                          ")

    tipoDici=input(colored("Desea cambiar el diccionario?, S o N: ",'green',attrs=['bold']))
    print("                                                                          ")

    if tipoDici.upper()=='S':
        print("                                                                          ")
        print(colored("Por favor indique nuevo diccionario,ejemplo password.txt",'green',attrs=['bold']))
        print(colored("Recuerde que debe de estar en el directorio ",'green',attrs=['bold']),colored("FichEnt",'blue',attrs=['bold']))
        print("                                                                          ")
        fileEnt=input(colored("Indique nombre del nuevo diccionario de passwords a utilizar: ",'green',attrs=['bold']))
    elif tipoDici.upper()=='N':
        fileEnt="diccionario.txt"
    else:
        print(colored("[-] Error opcion no valida",'red',attrs=['bold']))
        exit()

    #validamos fichero y lo leemos
    Fich_Ent_Passwd=validaFichEnt(fileEnt)
    passwdPosibles=leerFichPasswd(Fich_Ent_Passwd)

    try:
        for passw in passwdPosibles:
            print("Usuario : " + Usuariovictima)
            print("password: "******"[+]!!!! Password encontrada ¡¡¡¡ ",'green',attrs=['bold']) , colored(passw,'blue',attrs=['bold']) ,colored( " para usuario ",'green',attrs=['bold']),colored(Usuariovictima,'blue',attrs=['bold']),colored(" conexion a SSH",'green',attrs=['bold']))
                time.sleep(3)
                conexion_ssh.logout()
                exit()
            except pxssh.ExceptionPxssh as e:
                print(colored("[-]Contraeña erronea: IP: " + Ipvictima + ' Password: '******' Puerto:22','red',attrs=['bold']))

    except():
        print(colored("[-]Error de conexion SSH a la ip " +Ipvictima+ " puerto: 22",'red',attrs=['bold']))
        exit()
Beispiel #50
0
    def test_failed_custom_ssh_cmd(self):
        try:
            ssh = pxssh.pxssh()
            cipher_string = '-c invalid_cipher'
            result = ssh.login('server', 'me', password='******', cmd='ssh ' + cipher_string + ' -2')

            ssh.PROMPT = r'Closed connection'
            ssh.sendline('exit')
            ssh.prompt(timeout=5)
            string = str(ssh.before) + str(ssh.after)
    
            if 'Closed connection' not in string:
                assert False, 'should not have completed logging into Mock SSH client and exited'
        except pxssh.ExceptionPxssh as e:
            pass
        else:
            assert False, 'should have raised exception, pxssh.ExceptionPxssh'
Beispiel #51
0
def main(run):
    NET.CheckConnectionHost(init.var['target'], init.var['port'], 5)
    Loadingfile(init.var['dict'])

    with open(init.var['dict'], 'r') as passwords:
        for password in passwords:
            password = password.replace("\n", "")
            try:
                connect = pxssh.pxssh()
                connect.login(init.var['target'], init.var['user'], password)
                if True:
                    printk.suff("Successfully with [" + init.var['user'] +
                                "][" + password + "]\n")
                    UTIL.sRegister(init, password)
                    return
            except:
                printk.inf(" | Checking '" + password + "'")
	def Brightness(self):
		print('Getting Brightness Logs')
		self.lnk = pxssh.pxssh()
		self.lnk.login(self.Ref,self.username,self.password)
		self.lnk.sendline('cd ~/Desktop/') #TO DO: Correct Path for where brightness logs will be
		fname = 'Brighness.dat' #TO DO: Correct for actual file name
		self.lnk.sendline('scp %s [email protected]:/home/fhire/Desktop/FHiRE_GAM/logs' %fname)
		time.sleep(3)
		i = self.lnk.expect('[email protected]\'s password:'******'Pressure Logs Obtained')
Beispiel #53
0
def initialize_test_accounts():
    print('Initializing ida test accounts...')
    s = pxssh.pxssh(timeout=100)
    if not s.login(ida_host, ssh_user, ssh_password):
        print("SSH session failed on login.")
        print(str(s))
    else:
        print("SSH session login successful")
        command = 'cd /var/ida/utils; sudo -u apache /var/ida/utils/initialize_test_accounts'
        s.logfile = open('/tmp/shlog.log', 'wb')
        s.sendline(command)
        s.expect('.*assword.*', timeout=5)
        s.sendline(ssh_password)
        # pprint(s.prompt())
        # pprint(s.before)
        s.logout()
        print("Data initialized")
Beispiel #54
0
def tryPass(i, password_list):

    #password = input('password: '******'ls')
        #session.prompt()
        #print(session.before)

        session.logout()
        print(password_list[i] + " Worked")
        sys.exit(1)
    except pxssh.ExceptionPxssh:
        print(password_list[i] + " failed")
        session.close()
Beispiel #55
0
def server_ident(server, logNum):
    user = '******'
    passwd = 'root'
    print('{} Reboot Server {}'.format(logNum, server))
    rebootServers.reboot(cycle, logNum, server)
    time.sleep(90)
    print('{} Login to {} '.format(logNum, server))
    session = pxssh.pxssh()
    hs_session.login(session, server, user, passwd)
    command = 'SysManComm on'
    hs_session.power_ctl(cycle, logNum, session, server, command)
    time.sleep(120)
    hs_session.create_record(cycle, logNum, session, server)
    hs_session.get_available_cards(cycle, logNum, session, server)
    command = 'SysManComm off'
    hs_session.power_ctl(cycle, logNum, session, server, command)
    time.sleep(30)
Beispiel #56
0
def create_repository(repository_name, username, password, svn_hostname,
                      svn_host_user, svn_host_user_password):
    """Function to create a repository
    TODO: Find out how to store the SVN host name and passwords.

    COMMAND: cp -r /data/_repositories/_base_Repository_Template/ /data/_repositories/{0}; svnadmin setuuid /data/_repositories/{0}

    NOTE: Although this script creates the repositories,
    note that access to the repositories is administered via the script in
    svn://dllohsr222/XT4210/apps/get_svn_users_groups/get_users_groups.py
    Only users in the Production Redmine session who are added as
    members in a related project have access.
    """
    # first check if this exists.
    query = check_authorization(
        "svn://{}/{}".format(os.environ.get("SVN_SERVER", get_hostname()),
                             repository_name), username, password)

    if query.repo_exists:
        # If the repository exists, raise a FileExistsError (Python3+) or a NameError.
        error_message = "{} already exists. Cannot overwrite the repository!".format(
            repository_name)
        try:
            raise FileExistsError(error_message)
        except:
            raise NameError(error_message)
    else:
        if os.name == "nt":
            raise OSError(
                "This feature is unavailable on Windows based systems.")
        elif sys.version.startswith("2"):
            msg = ("This feature is not meant for "
                   "Python 2.x. Use Python 3.4+.")
            raise EnvironmentError(msg)
        else:
            # If the repository doesn't exist, and if this is called from a Linux host,
            # then create the repository.
            from pexpect import pxssh
            server = pxssh.pxssh()
            server.login(svn_hostname, svn_host_user, svn_host_user_password)
            commands = ("cp -r /data/_repositories/_base_Repository_Template/ "
                        "/data/_repositories/{0}; "
                        "svnadmin setuuid /data/_repositories/{0}"
                        ).format(repository_name)
            server.sendline(commands)
            server.logout()
Beispiel #57
0
def main():
    ip = '10.16.24.20'
    user = '******'
    passwd = 'CHGME.1'

    # my_f7_ssh = F7SshSession(ip, user, passwd)
    # my_f7_ssh.logout()
    s = pxssh()
    s.login(ip, user, passwd)
    s.sendline('uptime')
    s.prompt()
    print(s.before)
    s.sendline('who')
    s.prompt()
    print(s.before)
    s.logout()
    s.close()
Beispiel #58
0
 def ssh_connection(self):
     """Retrieve data from ASUSWRT via the ssh protocol."""
     from pexpect import pxssh
     try:
         ssh = pxssh.pxssh()
         ssh.login(self.host, self.username, self.password)
         ssh.sendline(_IP_NEIGH_CMD)
         ssh.prompt()
         neighbors = ssh.before.split(b'\n')[1:-1]
         ssh.sendline(_LEASES_CMD)
         ssh.prompt()
         leases_result = ssh.before.split(b'\n')[1:-1]
         ssh.logout()
         return (neighbors, leases_result)
     except pxssh.ExceptionPxssh as exc:
         _LOGGER.exception('Unexpected response from router: %s', exc)
         return ('', '')
 def svn_update(self, machine):
     addr_check = self.address_check(addr=self.address.get())
     result = askyesno(
         title='Update warning',
         message='You are going to update a prod machine. Make sure you '
         'inform your supervisors before!\rYour update path is {}'.format(
             self.address.get()),
         default='no')
     if result and addr_check:
         s = pxssh.pxssh()
         s.login(machine, copy_update_config.user_name,
                 copy_update_config.user_password)
         s.sendline('cd {}'.format(self.address.get()))
         s.prompt()
         s.sendline('svn update')
         self.new_windows(info='svn update')
         k = s.expect(['\'{}\':', 'Run.*'])
         if k == 0:
             s.sendline(copy_update_config.user_password)
         if k == 1:
             s.sendline('svn cleanup')
             s.prompt()
         g = s.expect([
             '.*{}\':'.format(copy_update_config.user_name), 'Run.*',
             pexpect.TIMEOUT
         ])
         s.prompt()
         if g == 0:
             s.sendline(copy_update_config.user_password)
             s.prompt(timeout=120)
             self.new_windows(info=(s.before))
         if g == 1:
             s.sendline('svn cleanup')
             s.expect(pexpect.EOF)
             s.expect('.*assword')
             s.sendline(copy_update_config.user_password)
             s.prompt()
             self.new_windows(info=(s.before))
         self.new_windows(info='Svn update complete!')
         self.create_logs(machine=machine,
                          move='svn update address:{}'.format(
                              self.address.get()))
     else:
         self.new_windows(info='Update aborted')
         self.create_logs(machine=machine, move='svn update aborted')
Beispiel #60
0
def shutdownvCenter_Kill(ip, vCenterID, type):
    """
    Führt einen Kill Befehl druch, um den vCenter Server herunterzufahren
    :param ip: die IP Adresse des ESXi Hosts, auf dem der vCenter Server läuft
    :param vCenterID: die WorldID des vCenter Servers
    :param type: der Type des Kill-Befehlts (soft, hard, force)
    """
    try:
        try:
            db = pymysql.connect(host='localhost',
                                 user='******',
                                 password='******',
                                 db='serverraum_temperaturueberwachung',
                                 autocommit=True)
            cursor = db.cursor()
            logging.info("Connected to database")
            cursor.execute(
                f'select benutzername, passwort from server where IP_Adresse = "{ip}";'
            )
            user = cursor.fetchone()[0]
            password = cursor.fetchone()[1]
            db.close()
        except Exception as e:
            logging.error(e)

        ssh = pxssh.pxssh()
        ssh.login(ip, user, password)
        logging.info(f"Mit ESXi[{ip}] verbunden")
        isRunning = False
        for data in getVMsOfHost(ip):
            vmip, id = data
            if id == vCenterID:
                isRunning = True

        if not isRunning:
            return

        ssh.sendline(
            f"esxcli vm process kill --type {type} --world-id= {vCenterID}")
        ssh.prompt()
        ssh.logout()
        logging.info(
            f'vCenter Server [{ip}] mit einem {type} Kill heruntergefahren')
    except pxssh.ExceptionPxssh as e:
        logging.error(e)