コード例 #1
0
    def copyNeededFiles(self):
        # Copying the files
        fileToCopy = self.getRepoFile()
        target = self.getRemoteName(self.AMBARI_REPO_FILENAME)

        self.host_log.write("Copying repo file to 'tmp' folder...")
        params = self.shared_state
        scp = SCP(params.user, params.sshkey_file, self.host, fileToCopy,
                  target, params.bootdir, self.host_log)
        retcode1 = scp.run()

        # Move file to repo dir
        self.host_log.write("Moving file to repo dir...")
        targetDir = self.getRepoDir()
        command = self.getMoveRepoFileCommand(targetDir)
        ssh = SSH(params.user, params.sshkey_file, self.host, command,
                  params.bootdir, self.host_log)
        retcode2 = ssh.run()

        self.host_log.write("Copying setup script file...")
        fileToCopy = params.action_agent_file
        target = self.getRemoteName(self.ACTION_SCRIPT_FILENAME)
        scp = SCP(params.user, params.sshkey_file, self.host, fileToCopy,
                  target, params.bootdir, self.host_log)
        retcode3 = scp.run()

        self.host_log.write("Copying files finished")
        return max(retcode1, retcode2, retcode3)
コード例 #2
0
def removeRequiretty(vm, pk_file):
    if not vm['master']:
        logger.info("Removing requiretty to VM: " + vm['ip'])
        try:
            private_key = vm['private_key']
            if pk_file:
                private_key = pk_file
            ssh_client = SSH(vm['ip'], vm['user'], vm['passwd'], private_key,
                             vm['remote_port'])
            # Activate tty mode to avoid some problems with sudo in REL
            ssh_client.tty = True
            sudo_pass = ""
            if ssh_client.password:
                sudo_pass = "******" + ssh_client.password + "' | "
            (stdout, stderr, code) = ssh_client.execute_timeout(
                sudo_pass +
                "sudo -S sed -i 's/.*requiretty$/#Defaults requiretty/' /etc/sudoers",
                5)
            logger.debug("OUT: " + stdout + stderr)
            return code == 0
        except:
            logger.exception("Error removing requiretty to VM: " + vm['ip'])
            return False
    else:
        return True
コード例 #3
0
  def copyNeededFiles(self):
    # Copying the files
    fileToCopy = self.getRepoFile()
    target = self.getRemoteName(self.AMBARI_REPO_FILENAME)

    self.host_log.write("Copying repo file to 'tmp' folder...")
    params = self.shared_state
    scp = SCP(params.user, params.sshkey_file, self.host, fileToCopy,
              target, params.bootdir, self.host_log)
    retcode1 = scp.run()

    # Move file to repo dir
    self.host_log.write("Moving file to repo dir...")
    targetDir = self.getRepoDir()
    command = self.getMoveRepoFileCommand(targetDir)
    ssh = SSH(params.user, params.sshkey_file, self.host, command,
              params.bootdir, self.host_log)
    retcode2 = ssh.run()

    self.host_log.write("Copying setup script file...")
    fileToCopy = params.action_agent_file
    target = self.getRemoteName(self.ACTION_SCRIPT_FILENAME)
    scp = SCP(params.user, params.sshkey_file, self.host, fileToCopy,
              target, params.bootdir, self.host_log)
    retcode3 = scp.run()

    self.host_log.write("Copying files finished")
    return max(retcode1, retcode2, retcode3)
コード例 #4
0
 def runActionAgent(self):
     params = self.shared_state
     self.host_log.write("Running agent action...")
     command = self.getRunActionCommand(self.host)
     ssh = SSH(params.user, params.sshkey_file, self.host, command,
               params.bootdir, self.host_log)
     retcode = ssh.run()
     self.host_log.write("Setting up agent finished")
     return retcode
コード例 #5
0
 def connect(self, event):
     password = self.password.get()
     host = self.host.get(self.host.curselection())
     self.ssh = SSH(host, self.login, password, self.port, self.auth_type,
                    self.key)
     if self.ssh.error != 0:
         tkinter.messagebox.showerror("Ошибка!", self.ssh.error)
     else:
         self.main_window(host)
コード例 #6
0
 def runActionAgent(self):
   params = self.shared_state
   self.host_log.write("Running agent action...")
   command = self.getRunActionCommand(self.host)
   ssh = SSH(params.user, params.sshkey_file, self.host, command,
             params.bootdir, self.host_log)
   retcode = ssh.run()
   self.host_log.write("Setting up agent finished")
   return retcode
コード例 #7
0
 def changePasswordFileModeOnHost(self):
     # Change password file mode to 600
     self.host_log.write("Changing password file mode...")
     params = self.shared_state
     command = "chmod 600 " + self.getPasswordFile()
     ssh = SSH(params.user, params.sshkey_file, self.host, command,
               params.bootdir, self.host_log)
     retcode = ssh.run()
     self.host_log.write("Change password file mode on host finished")
     return retcode
コード例 #8
0
 def changePasswordFileModeOnHost(self):
   # Change password file mode to 600
   self.host_log.write("Changing password file mode...")
   params = self.shared_state
   command = "chmod 600 " + self.getPasswordFile()
   ssh = SSH(params.user, params.sshkey_file, self.host, command,
             params.bootdir, self.host_log)
   retcode = ssh.run()
   self.host_log.write("Change password file mode on host finished")
   return retcode
コード例 #9
0
 def deletePasswordFile(self):
   # Deleting the password file
   self.host_log.write("Deleting password file...")
   params = self.shared_state
   command = "rm " + self.getPasswordFile()
   ssh = SSH(params.user, params.sshkey_file, self.host, command,
             params.bootdir, self.host_log)
   retcode = ssh.run()
   self.host_log.write("Deleting password file finished")
   return retcode
コード例 #10
0
 def deletePasswordFile(self):
     # Deleting the password file
     self.host_log.write("Deleting password file...")
     params = self.shared_state
     command = "rm " + self.getPasswordFile()
     ssh = SSH(params.user, params.sshkey_file, self.host, command,
               params.bootdir, self.host_log)
     retcode = ssh.run()
     self.host_log.write("Deleting password file finished")
     return retcode
コード例 #11
0
  def test_SSH(self, popenMock):
    params = SharedState("root", "sshkey_file", "scriptDir", "bootdir",
                                  "setupAgentFile", "ambariServer", "centos6",
                                  "1.2.1", "8440")
    host_log_mock = MagicMock()
    log = {'text': ""}
    def write_side_effect(text):
      log['text'] = log['text'] + text

    host_log_mock.write.side_effect = write_side_effect
    ssh = SSH(params.user, params.sshkey_file, "dummy-host", "dummy-command",
              params.bootdir, host_log_mock)
    log_sample = "log_sample"
    error_sample = "error_sample"
    # Successful run
    process = MagicMock()
    popenMock.return_value = process
    process.communicate.return_value = (log_sample, error_sample)
    process.returncode = 0

    retcode = ssh.run()

    self.assertTrue(popenMock.called)
    self.assertTrue(log_sample in log['text'])
    self.assertTrue(error_sample in log['text'])
    command_str = str(popenMock.call_args[0][0])
    self.assertEquals(command_str, "['ssh', '-o', 'ConnectTimeOut=60', '-o', "
            "'StrictHostKeyChecking=no', '-o', 'BatchMode=yes', '-tt', '-i', "
            "'sshkey_file', 'root@dummy-host', 'dummy-command']")
    self.assertEqual(retcode, 0)

    log['text'] = ""
    #unsuccessfull run
    process.returncode = 1

    retcode = ssh.run()

    self.assertTrue(log_sample in log['text'])
    self.assertTrue(error_sample in log['text'])
    self.assertEqual(retcode, 1)

    log['text'] = ""
    # unsuccessful run with error message
    process.returncode = 1

    dummy_error_message = "dummy_error_message"
    ssh = SSH(params.user, params.sshkey_file, "dummy-host", "dummy-command",
              params.bootdir, host_log_mock, errorMessage= dummy_error_message)
    retcode = ssh.run()

    self.assertTrue(log_sample in log['text'])
    self.assertTrue(error_sample in log['text'])
    self.assertTrue(dummy_error_message in log['text'])
    self.assertEqual(retcode, 1)
コード例 #12
0
 def checkSudoPackage(self):
   """ Checking 'sudo' package on remote host """
   params = self.shared_state
   command = "rpm -qa | grep sudo"
   ssh = SSH(params.user, params.sshkey_file, self.host, command,
             params.bootdir, self.host_log,
             errorMessage="Error: Sudo command is not available. " \
                          "Please install the sudo command.")
   retcode = ssh.run()
   self.host_log.write("Checking 'sudo' package finished")
   return retcode
コード例 #13
0
 def checkSudoPackage(self):
     """ Checking 'sudo' package on remote host """
     params = self.shared_state
     command = "rpm -qa | grep sudo"
     ssh = SSH(params.user, params.sshkey_file, self.host, command,
               params.bootdir, self.host_log,
               errorMessage="Error: Sudo command is not available. " \
                            "Please install the sudo command.")
     retcode = ssh.run()
     self.host_log.write("Checking 'sudo' package finished")
     return retcode
コード例 #14
0
    def runOsCheckScript(self):
        params = self.shared_state
        self.host_log.write("Running os type check...")
        command = "chmod a+x %s && %s %s" % \
                  (self.getOsCheckScriptRemoteLocation(),
                   self.getOsCheckScriptRemoteLocation(),  params.cluster_os_type)

        ssh = SSH(params.user, params.sshkey_file, self.host, command,
                  params.bootdir, self.host_log)
        retcode = ssh.run()
        self.host_log.write("Running os type check  finished")
        return retcode
コード例 #15
0
  def runOsCheckScript(self):
    params = self.shared_state
    self.host_log.write("Running os type check...")
    command = "chmod a+x %s && %s %s" % \
              (self.getOsCheckScriptRemoteLocation(),
               self.getOsCheckScriptRemoteLocation(),  params.cluster_os_type)

    ssh = SSH(params.user, params.sshkey_file, self.host, command,
              params.bootdir, self.host_log)
    retcode = ssh.run()
    self.host_log.write("Running os type check  finished")
    return retcode
コード例 #16
0
ファイル: starter.py プロジェクト: Skynet2-0/Skynet2.0
    def __init__(self, hostip, user, password, port=None, use_log=None):
        """
        Constructs the Starter which starts the program.

        hostip -- the ip address of the host.
        user -- the username of the user (Usually it will be host).
        password -- the password.
        port -- the port to connect to. (Default is None)
        use_log -- True for logging the starting. (Default is None)
        """
        if (use_log is None):
            self.ssh = SSH(hostip, user, password, port)
        else:
            self.ssh = SSH(hostip, user, password, port, use_log)
コード例 #17
0
ファイル: FileCreator.py プロジェクト: Skynet2-0/Skynet2.0
class FileCreator(object):
    """
    This class is responsable for creating files on the child server. It uses the SSH class to send them.
    """

    def __init__(self, hostip, user, password, port=None, use_log=None):
        """
        Constructs the FileCreator which starts the program.

        hostip -- the ip address of the host.
        user -- the username of the user (Usually it will be host).
        password -- the password.
        port -- the port to connect to. (Default is None)
        use_log -- True for logging the starting. (Default is None)
        """
        use_log = True
        if (use_log is None):
            self.ssh = SSH(hostip, user, password, port)
        else:
            self.ssh = SSH(hostip, user, password, port, use_log)

    def create(self, path, text):
        """ 
        creates a file at path with contents text. 
        example: createFile("~/file.txt", "test") will create a file named file.txt with contents "test" 
        """
        (_, out0, err0) = self.ssh.run('echo \"'+str(text)+'\" > '+str(path))
コード例 #18
0
ファイル: install.py プロジェクト: Skynet2-0/Skynet2.0
    def __init__(self, hostip, user, password, port=None, use_log=None):
        """
        Constructs the Installer.

        hostip -- the ip address of the host.
        user -- the username of the user (Usually it will be host).
        password -- the password.
        port -- the port to connect to. (Default is None)
        use_log -- True for logging the installation. (Default is None)
        """
        # self.ip = hostip
        # self.user = user
        # self.password = password
        if (use_log is None):
            self.ssh = SSH(hostip, user, password, port)
        else:
            self.ssh = SSH(hostip, user, password, port, use_log)
コード例 #19
0
ファイル: ctxt_agent.py プロジェクト: lxhiguera/im
def changeVMCredentials(vm, pk_file):
	if vm['os'] == "windows":
		#ansible -i hosts -m win_user -a "name=bob password=Password12345 groups=Users" all
		return False

	# Check if we must change user credentials in the VM
	if 'passwd' in vm and vm['passwd'] and 'new_passwd' in vm and vm['new_passwd']:
		logger.info("Changing password to VM: " + vm['ip'])
		private_key = vm['private_key']
		if pk_file:
			private_key = pk_file
		try:
			ssh_client = SSH(vm['ip'], vm['user'], vm['passwd'], private_key, vm['ssh_port'])
			(out, err, code) = ssh_client.execute('sudo bash -c \'echo "' + vm['user'] + ':' + vm['new_passwd'] + '" | /usr/sbin/chpasswd && echo "OK"\' 2> /dev/null')
		except:
			logger.exception("Error changing password to VM: " + vm['ip'] + ".")
			return False
		
		if code == 0:
			vm['passwd'] = vm['new_passwd']
			return True
		else:
			logger.error("Error changing password to VM: " + vm['ip'] + ". " + out + err)
			return False

	if 'new_public_key' in vm and vm['new_public_key'] and 'new_private_key' in vm and vm['new_private_key']:
		logger.info("Changing public key to VM: " + vm['ip'])
		private_key = vm['private_key']
		if pk_file:
			private_key = pk_file
		try:
			ssh_client = SSH(vm['ip'], vm['user'], vm['passwd'], private_key, vm['ssh_port'])
			(out, err, code) = ssh_client.execute('echo ' + vm['new_public_key'] + ' >> .ssh/authorized_keys')
		except:
			logger.exception("Error changing public key to VM: " + vm['ip'] + ".")
			return False
			
		if code != 0:
			logger.error("Error changing public key to VM:: " + vm['ip'] + ". " + out + err)
			return False
		else:
			vm['private_key'] = vm['new_private_key']
			return True

	return False
コード例 #20
0
ファイル: ctxt_agent.py プロジェクト: lxhiguera/im
def removeRequiretty(vm, pk_file):
	if not vm['master']:
		logger.info("Removing requiretty to VM: " + vm['ip'])
		try:
			private_key = vm['private_key']
			if pk_file:
				private_key = pk_file
			ssh_client = SSH(vm['ip'], vm['user'], vm['passwd'], private_key, vm['ssh_port'])
			# Activate tty mode to avoid some problems with sudo in REL
			ssh_client.tty = True
			(stdout, stderr, code) = ssh_client.execute("sudo sed -i 's/.*requiretty$/#Defaults requiretty/' /etc/sudoers")
			logger.debug("OUT: " + stdout + stderr)
			return code == 0
		except:
			logger.exception("Error removing requiretty to VM: " + vm['ip'])
			return False
	else:
		return True
コード例 #21
0
  def copyPasswordFile(self):
    # Copy the password file
    self.host_log.write("Copying password file to 'tmp' folder...")
    params = self.shared_state
    scp = SCP(params.user, params.sshkey_file, self.host, params.password_file,
              self.getPasswordFile(), params.bootdir, self.host_log)
    retcode1 = scp.run()

    self.copied_password_file = True

    # Change password file mode to 600
    self.host_log.write("Changing password file mode...")
    command = "chmod 600 " + self.getPasswordFile()
    ssh = SSH(params.user, params.sshkey_file, self.host, command,
              params.bootdir, self.host_log)
    retcode2 = ssh.run()

    self.host_log.write("Copying password file finished")
    return max(retcode1, retcode2)
コード例 #22
0
    def copyPasswordFile(self):
        # Copy the password file
        self.host_log.write("Copying password file to 'tmp' folder...")
        params = self.shared_state
        scp = SCP(params.user,
                  params.sshkey_file, self.host, params.password_file,
                  self.getPasswordFile(), params.bootdir, self.host_log)
        retcode1 = scp.run()

        self.copied_password_file = True

        # Change password file mode to 600
        self.host_log.write("Changing password file mode...")
        command = "chmod 600 " + self.getPasswordFile()
        ssh = SSH(params.user, params.sshkey_file, self.host, command,
                  params.bootdir, self.host_log)
        retcode2 = ssh.run()

        self.host_log.write("Copying password file finished")
        return max(retcode1, retcode2)
コード例 #23
0
ファイル: ctxt_agent.py プロジェクト: lxhiguera/im
def wait_ssh_access(vm):
	"""
	 Test the SSH access to the VM
	"""
	delay = 10
	wait = 0
	success = False
	res = None
	last_tested_private = False
	while wait < SSH_WAIT_TIMEOUT:
		if 'private_ip' in vm and not last_tested_private:
			# First test the private one
			vm_ip = vm['private_ip']
			last_tested_private = True
		else:
			vm_ip = vm['ip']
			last_tested_private = False
		logger.debug("Testing SSH access to VM: " + vm_ip)
		wait += delay
		try:
			ssh_client = SSH(vm_ip, vm['user'], vm['passwd'], vm['private_key'], vm['ssh_port'])
			success = ssh_client.test_connectivity()
			res = 'init'
		except AuthenticationException:
			try_ansible_key = True
			if 'new_passwd' in vm:
				try_ansible_key = False
				# If the process of changing credentials has finished in the VM, we must use the new ones
				logger.warn("Error connecting with SSH with initial credentials with: " + vm_ip + ". Try to use new ones.")
				try:
					ssh_client = SSH(vm_ip, vm['user'], vm['new_passwd'], vm['private_key'], vm['ssh_port'])
					success = ssh_client.test_connectivity()
					res = "new"
				except AuthenticationException:
					try_ansible_key = True
			
			if try_ansible_key:
				# In some very special cases the last two cases fail, so check if the ansible key works 
				logger.warn("Error connecting with SSH with initial credentials with: " + vm_ip + ". Try to ansible_key.")
				try:
					ssh_client = SSH(vm_ip, vm['user'], None, PK_FILE, vm['ssh_port'])
					success = ssh_client.test_connectivity()
					res = 'pk_file'
				except:
					logger.exception("Error connecting with SSH with: " + vm_ip)
					success = False
			
		if success:
			vm['ip'] = vm_ip
			return res
		else:
			time.sleep(delay)
	
	return None
コード例 #24
0
ファイル: starter.py プロジェクト: Skynet2-0/Skynet2.0
class Starter(object):
    """
    This class is responsable for sending the startup commands to
    the child server. It uses the SSH class to send them.
    """

    def __init__(self, hostip, user, password, port=None, use_log=None):
        """
        Constructs the Starter which starts the program.

        hostip -- the ip address of the host.
        user -- the username of the user (Usually it will be host).
        password -- the password.
        port -- the port to connect to. (Default is None)
        use_log -- True for logging the starting. (Default is None)
        """
        if (use_log is None):
            self.ssh = SSH(hostip, user, password, port)
        else:
            self.ssh = SSH(hostip, user, password, port, use_log)

    def start(self, otherCore = None):
        """ Starts the program. """
        self.start_other_requirements()
        if otherCore:
            self.start_agent("agent/"+otherCore+" -x True -t False")
        else:            
            self.start_agent("agent/agentCore.py -x True -t False")

    def start_other_requirements(self):
        self.ssh.run('''(Xvfb :99 -ac &> /dev/null &)''')
        
        self.ssh.run('''(cd ~/Skynet2.0 && export DISPLAY=:99 && java -jar selenium-server-standalone-2.53.0.jar &>log.out &)''')

    def start_agent(self, relAgentPath):
        """
        given the path to the agent program starting from ~/Skynet2.0 runs this agent
        """
        self.ssh.run('(cd ~/Skynet2.0 && PYTHONPATH=${PYTHONPATH}:. python ' + relAgentPath + ' &>>agentCore.out &)')
コード例 #25
0
 def changeRootPasswd(self, newPasswd):
     ssh = SSH(self.ip_address)
     ssh.changePasswd(newPasswd)
コード例 #26
0
ファイル: ImportModule.py プロジェクト: try-dash-now/idash
except Exception as e:
    print(traceback.format_exc())
from powershell import powershell

try:
    ps = powershell("a", {}, logpath=logpath)
    ps.SessionAlive = False
except Exception as e:
    print(traceback.format_exc())
    ps.SessionAlive = False


from SSH import SSH

try:
    ps = SSH("a", {}, logpath=logpath)
    ps.SessionAlive = False
except Exception as e:
    ps.SessionAlive = False
    print(traceback.format_exc())

import Tkinter


class tcltk(Tkinter.Tk):
    def __init__(self):
        Tkinter.Tk.__init__(self, None, None, "Tk", 0)


tcltk()
os._exit(0)
コード例 #27
0
ファイル: docker.py プロジェクト: alanpaiva/python4linux
 def __init__(self):
     SSH.__init__(self)
コード例 #28
0
ファイル: ImportModule.py プロジェクト: try-dash-now/idash
    chan = client.invoke_shell()

except Exception as e:
    print(traceback.format_exc())
from powershell import powershell
try:
    ps = powershell('a', {}, logpath=logpath)
    ps.SessionAlive=False
except Exception as e:
    print(traceback.format_exc())
    ps.SessionAlive=False


from SSH import SSH
try:
    ps = SSH('a', {}, logpath=logpath)
    ps.SessionAlive=False
except Exception as e:
    ps.SessionAlive=False
    print(traceback.format_exc())

import Tkinter
class tcltk(Tkinter.Tk):
    def __init__(self):
        Tkinter.Tk.__init__(self, None, None, 'Tk', 0)
tcltk()
os._exit(0)



コード例 #29
0
ファイル: ctxt_agent.py プロジェクト: buweixiaomi/im
def contextualize_vm(general_conf_data, vm_conf_data):
    res_data = {}
    logger.info('Generate and copy the ssh key')

    # If the file exists, do not create it again
    if not os.path.isfile(PK_FILE):
        out = run_command('ssh-keygen -t rsa -C ' +
                          getpass.getuser() + ' -q -N "" -f ' + PK_FILE)
        logger.debug(out)

    # Check that we can SSH access the node
    ctxt_vm = None
    for vm in general_conf_data['vms']:
        if vm['id'] == vm_conf_data['id']:
            ctxt_vm = vm

    if not ctxt_vm:
        logger.error("No VM to Contextualize!")
        res_data['OK'] = False
        return res_data

    for task in vm_conf_data['tasks']:
        task_ok = False
        num_retries = 0
        while not task_ok and num_retries < PLAYBOOK_RETRIES:
            num_retries += 1
            logger.info('Launch task: ' + task)
            if ctxt_vm['os'] == "windows":
                # playbook = general_conf_data['conf_dir'] + "/" + task + "_task_all_win.yml"
                playbook = general_conf_data[
                    'conf_dir'] + "/" + task + "_task.yml"
            else:
                playbook = general_conf_data[
                    'conf_dir'] + "/" + task + "_task_all.yml"
            inventory_file = general_conf_data['conf_dir'] + "/hosts"

            ansible_thread = None
            if task == "basic":
                # This is always the fist step, so put the SSH test, the
                # requiretty removal and change password here
                for vm in general_conf_data['vms']:
                    if vm['os'] == "windows":
                        logger.info("Waiting WinRM access to VM: " + vm['ip'])
                        ssh_res = wait_winrm_access(vm)
                    else:
                        logger.info("Waiting SSH access to VM: " + vm['ip'])
                        ssh_res = wait_ssh_access(vm)

                    # the IP has changed public for private and we are the
                    # master VM
                    if 'ctxt_ip' in vm and vm['ctxt_ip'] != vm['ip'] and ctxt_vm['master']:
                        # update the ansible inventory
                        logger.info("Changing the IP %s for %s in config files." % (
                            vm['ctxt_ip'], vm['ip']))
                        replace_vm_ip(vm)

                    if vm['id'] == vm_conf_data['id']:
                        cred_used = ssh_res
                    if not ssh_res:
                        logger.error("Error Waiting access to VM: " + vm['ip'])
                        res_data['SSH_WAIT'] = False
                        res_data['OK'] = False
                        return res_data
                    else:
                        res_data['SSH_WAIT'] = True
                        logger.info("Remote access to VM: " +
                                    vm['ip'] + " Open!")

                # The basic task uses the credentials of VM stored in ctxt_vm
                pk_file = None
                if cred_used == "pk_file":
                    pk_file = PK_FILE

                # First remove requiretty in the node
                if ctxt_vm['os'] != "windows":
                    success = removeRequiretty(ctxt_vm, pk_file)
                    if success:
                        logger.info("Requiretty successfully removed")
                    else:
                        logger.error("Error removing Requiretty")

                # Check if we must chage user credentials
                # Do not change it on the master. It must be changed only by
                # the ConfManager
                change_creds = False
                if not ctxt_vm['master']:
                    change_creds = changeVMCredentials(ctxt_vm, pk_file)
                    res_data['CHANGE_CREDS'] = change_creds

                if ctxt_vm['os'] != "windows":
                    # this step is not needed in windows systems
                    ansible_thread = LaunchAnsiblePlaybook(
                        logger, playbook, ctxt_vm, 2, inventory_file, pk_file, INTERNAL_PLAYBOOK_RETRIES, change_creds)
            else:
                # In some strange cases the pk_file disappears. So test it and
                # remake basic recipe
                if ctxt_vm['os'] != "windows":
                    success = False
                    try:
                        ssh_client = SSH(ctxt_vm['ip'], ctxt_vm[
                                         'user'], None, PK_FILE, ctxt_vm['remote_port'])
                        success = ssh_client.test_connectivity()
                    except:
                        success = False

                    if not success:
                        logger.warn("Error connecting with SSH using the ansible key with: " + ctxt_vm[
                                    'ip'] + ". Call the basic playbook again.")
                        basic_playbook = general_conf_data[
                            'conf_dir'] + "/basic_task_all.yml"
                        output_basic = StringIO()
                        ansible_thread = LaunchAnsiblePlaybook(output_basic, basic_playbook, ctxt_vm, 2,
                                                               inventory_file, None, INTERNAL_PLAYBOOK_RETRIES, True)
                        ansible_thread.join()

                # in the other tasks pk_file can be used
                ansible_thread = LaunchAnsiblePlaybook(logger, playbook, ctxt_vm, 2, inventory_file, PK_FILE,
                                                       INTERNAL_PLAYBOOK_RETRIES, vm_conf_data['changed_pass'])

            if ansible_thread:
                (task_ok, _) = wait_thread(ansible_thread)
            else:
                task_ok = True
            if not task_ok:
                logger.warn("ERROR executing task %s: (%s/%s)" %
                            (task, num_retries, PLAYBOOK_RETRIES))
            else:
                logger.info('Task %s finished successfully' % task)

        res_data[task] = task_ok
        if not task_ok:
            res_data['OK'] = False
            return res_data

    res_data['OK'] = True

    logger.info('Process finished')
    return res_data
コード例 #30
0
def wait_ssh_access(vm):
    """
     Test the SSH access to the VM
    """
    delay = 10
    wait = 0
    success = False
    res = None
    last_tested_private = False
    while wait < SSH_WAIT_TIMEOUT:
        if 'ctxt_ip' in vm:
            vm_ip = vm['ctxt_ip']
        elif 'private_ip' in vm and not last_tested_private:
            # First test the private one
            vm_ip = vm['private_ip']
            last_tested_private = True
        else:
            vm_ip = vm['ip']
            last_tested_private = False
        logger.debug("Testing SSH access to VM: " + vm_ip)
        wait += delay
        try:
            ssh_client = SSH(vm_ip, vm['user'], vm['passwd'],
                             vm['private_key'], vm['remote_port'])
            success = ssh_client.test_connectivity()
            res = 'init'
        except AuthenticationException:
            try_ansible_key = True
            if 'new_passwd' in vm:
                try_ansible_key = False
                # If the process of changing credentials has finished in the
                # VM, we must use the new ones
                logger.debug(
                    "Error connecting with SSH with initial credentials with: "
                    + vm_ip + ". Try to use new ones.")
                try:
                    ssh_client = SSH(vm_ip, vm['user'], vm['new_passwd'],
                                     vm['private_key'], vm['remote_port'])
                    success = ssh_client.test_connectivity()
                    res = "new"
                except AuthenticationException:
                    try_ansible_key = True

            if try_ansible_key:
                # In some very special cases the last two cases fail, so check
                # if the ansible key works
                logger.debug(
                    "Error connecting with SSH with initial credentials with: "
                    + vm_ip + ". Try to ansible_key.")
                try:
                    ssh_client = SSH(vm_ip, vm['user'], None, PK_FILE,
                                     vm['remote_port'])
                    success = ssh_client.test_connectivity()
                    res = 'pk_file'
                except:
                    logger.exception("Error connecting with SSH with: " +
                                     vm_ip)
                    success = False

        if success:
            vm['ctxt_ip'] = vm_ip
            return res
        else:
            time.sleep(delay)

    return None
コード例 #31
0
def changeVMCredentials(vm, pk_file):
    if vm['os'] == "windows":
        if 'passwd' in vm and vm['passwd'] and 'new_passwd' in vm and vm[
                'new_passwd']:
            try:
                import winrm
                url = "https://" + vm['ip'] + ":5986"
                s = winrm.Session(url, auth=(vm['user'], vm['passwd']))
                r = s.run_cmd('net', ['user', vm['user'], vm['new_passwd']])

                # this part of the code is never reached ...
                if r.status_code == 0:
                    vm['passwd'] = vm['new_passwd']
                    return True
                else:
                    logger.error("Error changing password to Windows VM: " +
                                 r.std_out)
                    return False
            except winrm.exceptions.AuthenticationError:
                # if the password is correctly changed the command returns this
                # error
                try:
                    # let's check that the new password works
                    s = winrm.Session(url, auth=(vm['user'], vm['new_passwd']))
                    r = s.run_cmd('echo', ['OK'])
                    if r.status_code == 0:
                        vm['passwd'] = vm['new_passwd']
                        return True
                    else:
                        logger.error(
                            "Error changing password to Windows VM: " +
                            r.std_out)
                        return False
                except:
                    logger.exception(
                        "Error changing password to Windows VM: " + vm['ip'] +
                        ".")
                    return False
            except:
                logger.exception("Error changing password to Windows VM: " +
                                 vm['ip'] + ".")
                return False
    else:  # Linux VMs
        # Check if we must change user credentials in the VM
        if 'passwd' in vm and vm['passwd'] and 'new_passwd' in vm and vm[
                'new_passwd']:
            logger.info("Changing password to VM: " + vm['ip'])
            private_key = vm['private_key']
            if pk_file:
                private_key = pk_file
            try:
                ssh_client = SSH(vm['ip'], vm['user'], vm['passwd'],
                                 private_key, vm['remote_port'])
                (out, err, code) = ssh_client.execute(
                    'sudo bash -c \'echo "' + vm['user'] + ':' +
                    vm['new_passwd'] +
                    '" | /usr/sbin/chpasswd && echo "OK"\' 2> /dev/null')
            except:
                logger.exception("Error changing password to VM: " + vm['ip'] +
                                 ".")
                return False

            if code == 0:
                vm['passwd'] = vm['new_passwd']
                return True
            else:
                logger.error("Error changing password to VM: " + vm['ip'] +
                             ". " + out + err)
                return False

        if 'new_public_key' in vm and vm[
                'new_public_key'] and 'new_private_key' in vm and vm[
                    'new_private_key']:
            logger.info("Changing public key to VM: " + vm['ip'])
            private_key = vm['private_key']
            if pk_file:
                private_key = pk_file
            try:
                ssh_client = SSH(vm['ip'], vm['user'], vm['passwd'],
                                 private_key, vm['remote_port'])
                (out, err,
                 code) = ssh_client.execute('echo ' + vm['new_public_key'] +
                                            ' >> .ssh/authorized_keys')
            except:
                logger.exception("Error changing public key to VM: " +
                                 vm['ip'] + ".")
                return False

            if code != 0:
                logger.error("Error changing public key to VM:: " + vm['ip'] +
                             ". " + out + err)
                return False
            else:
                vm['private_key'] = vm['new_private_key']
                return True

    return False
コード例 #32
0
ファイル: install.py プロジェクト: Skynet2-0/Skynet2.0
class Installer(object):
    """
    This class is responsable for sending the install commands to the child
    server.

    It uses the SSH class to send them.
    """

    def __init__(self, hostip, user, password, port=None, use_log=None):
        """
        Constructs the Installer.

        hostip -- the ip address of the host.
        user -- the username of the user (Usually it will be host).
        password -- the password.
        port -- the port to connect to. (Default is None)
        use_log -- True for logging the installation. (Default is None)
        """
        # self.ip = hostip
        # self.user = user
        # self.password = password
        if (use_log is None):
            self.ssh = SSH(hostip, user, password, port)
        else:
            self.ssh = SSH(hostip, user, password, port, use_log)

    def install(self, otherBranch = None):
        """
        Makes the class install itself through SSH.

        It also starts running the class.
        """
        print('Start installing.')
        (_, out0, err0) = self.ssh.run('apt-get update')
        self.ssh._checkStreams(out0, err0, 'apt update failed', 'apt updated.')
        (_, out0, err0) = self.ssh.run('apt-get install -y --force-yes git')
        self.ssh._checkStreams(out0, err0, 'git install failed', 'git installed.')
        command = 'git clone --recursive https://github.com/Skynet2-0/Skynet2.0.git'
        (_, out0, err0) = self.ssh.run(command)
        self.ssh._checkStreams(out0, err0, 'git clone failed', 'project cloned.')
        if isinstance(otherBranch, basestring):
            command = 'cd ~/Skynet2.0 && git checkout '+otherBranch
            (_, out0, err0) = self.ssh.run(command)
            self.ssh._checkStreams(out0, err0, 'git checkout failed', 'git checkout succeeeded.')
        command = """cd ~/Skynet2.0 && sh build.sh >> build.out"""
        print("starting the actual installing of programs on the child, this can take up to 15 minutes.")
        (_, out0, err0) = self.ssh.run(command)
        self.ssh._checkStreams_until_done(out0, err0, 'Preqrequisite installation failed', 'Preqrequisite installation succesfull.')
        print('Installation finished.')



    def finish(self):
        "Does some clean up."
        self.ssh.close_connection()
コード例 #33
0
 def changeRootPasswd(self, newPasswd):
     ssh = SSH(self.ip_address)
     ssh.changePasswd(newPasswd)
コード例 #34
0
    for loja_list in lojas:
        caixas_list = loja_list[1]

        for caixas in caixas_list:
            for caixa in caixas:
                loja = loja_list[0]
                ssh_ip = '192.168.' + caixas[1]
                ssh_hostname = caixas[0]
                password_index = caixas[2]

                c = Command(password_index)
                ssh_password = f.getBaseVariables('password')[password_index]

                try:
                    ssh = SSH(ssh_ip, ssh_hostname, ssh_password)
                except Exception:
                    errors.append('Falha na conexão SSH com o \033[1m' +
                                  ssh_hostname + ' loja0' + loja + '\033[0;0m')
                    break

                try:
                    print('\033[1m\033[94m[Loja ' + loja + '][' +
                          ssh_hostname + ']\n\033[0m')
                    # Insira os COMANDOS/FUNÇÕES aqui
                    c.isPinging(ssh_ip)
                    #
                    print('---\n')
                except Exception:
                    errors.append(
                        'Falha na execução do comando com o \033[1m' +
コード例 #35
0
class GUI:
    def __init__(self):
        self.password = None
        self.host = None
        self.find_number = [
            None,
        ]
        self.find_date = None
        self.find_text_add = []
        self.ssh = None
        self.result = None
        self.win = None
        self.btn_del_ent = None
        self.btn_frame = None
        self.ent_frame = None
        self.find_number_frame = None
        self.find_date_frame = None
        self.find_file_frame = None
        self.data_frame = None
        self.scr = None
        self.file = None
        self.files = None

        logger_conf = json.load(open("logger_conf.json"))
        self.auth_type = logger_conf["Auth_type"]
        self.login = logger_conf["Login"]
        self.port = logger_conf["Port"]
        self.key = logger_conf["SSH_keyFile"]
        self.hosts = logger_conf["Hosts"]
        self.files = logger_conf["Files"]
        self.files_path = logger_conf["Files_path"]
        self.window_width = int(logger_conf["Window_width"])
        self.window_height = int(logger_conf["Window_height"])

        self.root = tkinter.Tk()
        self.root.title("Logger")
        self.auth()
        self.root.mainloop()

    def connect(self, event):
        password = self.password.get()
        host = self.host.get(self.host.curselection())
        self.ssh = SSH(host, self.login, password, self.port, self.auth_type,
                       self.key)
        if self.ssh.error != 0:
            tkinter.messagebox.showerror("Ошибка!", self.ssh.error)
        else:
            self.main_window(host)

    def auth(self):
        password_text = tkinter.Label(self.root,
                                      text="Введите пароль",
                                      font="Arial 11")  # строка текста
        self.password = tkinter.Entry(self.root, width=20, bd=3, show='*')
        self.password.focus_set()

        btn = tkinter.Button(self.root, text="Войти")
        btn.bind("<Button-1>", self.connect)  # связь кнопки и функции
        self.root.bind("<Return>", self.connect)

        self.host = tkinter.Listbox(self.root,
                                    selectmode=tkinter.SINGLE,
                                    height=4)
        for i in self.hosts:
            self.host.insert(tkinter.END, i)

        if self.auth_type == 'password':
            password_text.pack(padx=5, pady=5)
            self.password.pack()
        self.host.pack(padx=10, pady=10)
        btn.pack(padx=10, pady=10)

    def main_window(self, title):
        self.win = tkinter.Toplevel(self.root)
        self.ent_frame = tkinter.Frame(self.win)
        self.btn_frame = tkinter.Frame(self.win)
        self.find_date_frame = tkinter.Frame(self.ent_frame)
        self.find_number_frame = tkinter.Frame(self.ent_frame)
        self.find_file_frame = tkinter.Frame(self.ent_frame)
        self.win.title(title)
        self.win.minsize(width=self.window_width, height=self.window_height)
        text = tkinter.Label(self.win, text="Искать", font="Arial 9")

        find_file_text = tkinter.Label(self.find_file_frame,
                                       text="Файл",
                                       font="Arial 9")
        self.file = tkinter.Listbox(self.find_file_frame,
                                    selectmode=tkinter.SINGLE,
                                    height=3)
        for i in self.files:
            self.file.insert(tkinter.END, i)

        find_number_text = tkinter.Label(self.find_number_frame,
                                         text="Критерий поиска",
                                         font="Arial 9")
        self.find_number[0] = tkinter.Entry(self.find_number_frame,
                                            width=20,
                                            bd=3)
        self.find_number[0].focus_set()
        find_date_text = tkinter.Label(self.find_date_frame,
                                       text="Дата",
                                       font="Arial 9")
        self.find_date = tkinter.Entry(self.find_date_frame, width=20, bd=3)
        btn = tkinter.Button(self.btn_frame, text="Найти")
        btn.bind("<Button-1>", self.grep)
        self.win.bind("<Return>", self.grep)

        self.data_frame = tkinter.Frame(self.win)
        self.result = tkinter.Text(self.data_frame,
                                   width=115,
                                   height=27,
                                   font="Arial 9")
        self.result.insert(1.0, '')
        self.scr = tkinter.Scrollbar(self.data_frame,
                                     command=self.result.yview)
        self.result.configure(yscrollcommand=self.scr.set)
        btn_add_ent = tkinter.Button(self.btn_frame,
                                     text="Добавить критерий поиска")
        btn_add_ent.bind("<Button-1>", self.add_ent)

        text.pack(padx=5, pady=5)
        self.find_file_frame.pack(side=tkinter.LEFT)
        find_file_text.pack()
        self.file.pack(side=tkinter.LEFT, padx=5, pady=5)
        self.find_date_frame.pack(side=tkinter.LEFT)
        find_date_text.pack()
        self.find_number_frame.pack(side=tkinter.LEFT)
        find_number_text.pack()
        self.find_date.pack(side=tkinter.LEFT, padx=5, pady=5)
        self.find_number[0].pack(side=tkinter.LEFT, padx=5, pady=5)
        self.ent_frame.pack()
        self.btn_frame.pack()
        btn.pack(side=tkinter.LEFT, padx=5, pady=5)
        btn_add_ent.pack(side=tkinter.LEFT, padx=5, pady=5)
        self.data_frame.pack()
        # self.result.pack(padx=5, pady=5)
        self.result.grid(row=0, column=0)
        self.scr.grid(row=0, column=1)

    def grep(self, event):
        date = self.find_date.get()

        if date == '':
            pass
        elif not (date.isdigit()):
            tkinter.messagebox.showerror(
                "Ошибка!", "В поле дата нужно ввести дату в формате: ГГГГММДД")

        if len(self.find_number) == 1:
            number = self.find_number[0].get()
        else:
            number = []
            for i in self.find_number:
                number.append(i.get())
        file = self.file.get(self.file.curselection())
        result = self.ssh.grep(number, file, date, self.files_path)
        self.result.pack_forget()
        # self.result = tkinter.Label(self.win, text=result, font="Arial 9")
        self.result.insert(tkinter.CURRENT, result)
        self.result.grid(row=0, column=0)
        self.scr.grid(row=0, column=1)

    def add_ent(self, event):
        self.find_number.append(
            tkinter.Entry(self.find_number_frame, width=20, bd=3))
        self.find_text_add.append(self.find_number[-1])
        for i in self.find_text_add:
            i.pack(side=tkinter.LEFT, padx=5, pady=5)
        if len(self.find_text_add) == 1:
            self.btn_del_ent = tkinter.Button(self.btn_frame,
                                              text="Удалить критерий поиска")
            self.btn_del_ent.bind("<Button-1>", self.del_ent)
            self.btn_del_ent.pack(side=tkinter.LEFT, padx=5, pady=5)

    def del_ent(self, event):
        self.find_text_add[-1].pack_forget()
        del (self.find_text_add[-1])
        del (self.find_number[-1])
        if len(self.find_text_add) < 1:
            self.btn_del_ent.pack_forget()
コード例 #36
0
def worker():
    while True:
        try:
            data = jobs_queue.get()
            print "data",data[0]
            job = data[0]
            ssh = SSH()
            interval = job.interval
            enabled = job.enabled
            ssh_machine = job.ssh_machine.split(',')
            ssh_username = job.ssh_username
            ssh_password = job.ssh_password
            directory = job.directory.split(',')
            sudo = job.sudo
            tar = job.tar
            tar_location=job.tar_location
            status, output, error = None, None, None
            epochTime = get_epoch_time()
            if enabled:
                count = 0
                offsets_queue = []
                job_details = get_job_details(job)
                logging.info("Job[%s]: Starting job... interval=%s, directory=%s, sudo=%s, tar=%s, tarLocation=%s" % (
                jobid, interval, directory,sudo, tar,tar_location))
                while True:
                    for ip in ssh_machine:
                        for file in directory:
                            #command = "/bin/rm -rf %s" %  (file)
                            #logging.info("Executing: %s" % command)
                            tarFileName=file.split('/')[-1]
                            print tarFileName
                            tarLocation=file.rsplit('/',1)[:1][0]
                            pstTime = get_pst_time()
                            tarCommand = "[ -f %s ] && cd  %s && tar -cvzf %s_%s.tar.gz %s --remove-files" %(file,tarLocation,tarFileName,pstTime,tarFileName)
                            logging.info("Tar command executed is: %s" % tarCommand)
                            logging.info("Tar files are stored in the location: %s" %tarLocation)
                            status, output, error = None, None, None
                            try:
                                if sudo:
                                    if tar :
                                        status, output = ssh.run_sudo_command(ssh_username=ssh_username, ssh_password=ssh_password,
                                                                                  ssh_machine=ip, command=tarCommand, jobid=jobid)
                                        logging.info("Tar Command Executed is : %s , output of tar command : %s" % (tarCommand,output))
                                        listStatus=check_list_empty(output)
                                        write_log_info(listStatus, output)
                                    else:
                                        status, output = ssh.run_sudo_command(ssh_username=ssh_username, ssh_password=ssh_password,
                                                                                  ssh_machine=ip, command=command, jobid=jobid)
                                        logging.info("Tar Command Executed is : %s , output of tar command : %s" % (tarCommand,output))
                                        listStatus=check_list_empty(output)
                                        write_log_info(listStatus, output)  
                                else:
                                    if tar:
                                        status, output = ssh.run_command(ssh_username=ssh_username, ssh_password=ssh_password,
                                                                         ssh_machine=ip, command=tarCommand, jobid=jobid,
                                                                         job_details=job_details)
                                        logging.info("Tar Command Executed is : %s , output of tar command : %s" % (tarCommand,output))
                                        listStatus=check_list_empty(output)
                                        write_log_info(listStatus, output)
                                    else:
                                        status, output = ssh.run_command(ssh_username=ssh_username, ssh_password=ssh_password,
                                                                         ssh_machine=ip, command=command, jobid=jobid,
                                                                         job_details=job_details)
                                        listStatus=check_list_empty(output)
                                        write_log_info(listStatus, output)  
                            except ValueError:
                                logging.error("Job[%s]: Could not run command:%s" % (jobid, sys.exc_info()[0]))
                                logging.error(traceback.format_exc())
                                error = str(traceback.format_exc())
                                print error
                                status = False
                            logging.info("Job[%s]: Sleeping for %s secs..." % (jobid, interval))
                    sleep(interval)
            else:
                logging.info("Job[%s]: Is set to disable state." % jobid)
        except:
            #logging.error("Job[%s]: Unexpected error:%s, output:%s" % (jobid, sys.exc_info()[0], output))
            logging.error(traceback.format_exc())
        finally:
            jobs_queue.task_done()
コード例 #37
0
def contextualize_vm(general_conf_data, vm_conf_data):
    res_data = {}
    logger.info('Generate and copy the ssh key')

    # If the file exists, do not create it again
    if not os.path.isfile(PK_FILE):
        out = run_command('ssh-keygen -t rsa -C ' + getpass.getuser() +
                          ' -q -N "" -f ' + PK_FILE)
        logger.debug(out)

    # Check that we can SSH access the node
    ctxt_vm = None
    for vm in general_conf_data['vms']:
        if vm['id'] == vm_conf_data['id']:
            ctxt_vm = vm

    if not ctxt_vm:
        logger.error("No VM to Contextualize!")
        res_data['OK'] = False
        return res_data

    for task in vm_conf_data['tasks']:
        task_ok = False
        num_retries = 0
        while not task_ok and num_retries < PLAYBOOK_RETRIES:
            num_retries += 1
            logger.info('Launch task: ' + task)
            if ctxt_vm['os'] == "windows":
                # playbook = general_conf_data['conf_dir'] + "/" + task + "_task_all_win.yml"
                playbook = general_conf_data[
                    'conf_dir'] + "/" + task + "_task.yml"
            else:
                playbook = general_conf_data[
                    'conf_dir'] + "/" + task + "_task_all.yml"
            inventory_file = general_conf_data['conf_dir'] + "/hosts"

            ansible_thread = None
            if task == "basic":
                # This is always the fist step, so put the SSH test, the
                # requiretty removal and change password here
                for vm in general_conf_data['vms']:
                    if vm['os'] == "windows":
                        logger.info("Waiting WinRM access to VM: " + vm['ip'])
                        ssh_res = wait_winrm_access(vm)
                    else:
                        logger.info("Waiting SSH access to VM: " + vm['ip'])
                        ssh_res = wait_ssh_access(vm)

                    # the IP has changed public for private and we are the
                    # master VM
                    if 'ctxt_ip' in vm and vm['ctxt_ip'] != vm[
                            'ip'] and ctxt_vm['master']:
                        # update the ansible inventory
                        logger.info(
                            "Changing the IP %s for %s in config files." %
                            (vm['ctxt_ip'], vm['ip']))
                        replace_vm_ip(vm)

                    if vm['id'] == vm_conf_data['id']:
                        cred_used = ssh_res
                    if not ssh_res:
                        logger.error("Error Waiting access to VM: " + vm['ip'])
                        res_data['SSH_WAIT'] = False
                        res_data['OK'] = False
                        return res_data
                    else:
                        res_data['SSH_WAIT'] = True
                        logger.info("Remote access to VM: " + vm['ip'] +
                                    " Open!")

                # The basic task uses the credentials of VM stored in ctxt_vm
                pk_file = None
                if cred_used == "pk_file":
                    pk_file = PK_FILE

                # First remove requiretty in the node
                if ctxt_vm['os'] != "windows":
                    success = removeRequiretty(ctxt_vm, pk_file)
                    if success:
                        logger.info("Requiretty successfully removed")
                    else:
                        logger.error("Error removing Requiretty")

                # Check if we must chage user credentials
                # Do not change it on the master. It must be changed only by
                # the ConfManager
                change_creds = False
                if not ctxt_vm['master']:
                    change_creds = changeVMCredentials(ctxt_vm, pk_file)
                    res_data['CHANGE_CREDS'] = change_creds

                if ctxt_vm['os'] != "windows":
                    # this step is not needed in windows systems
                    ansible_thread = LaunchAnsiblePlaybook(
                        logger, playbook, ctxt_vm, 2, inventory_file, pk_file,
                        INTERNAL_PLAYBOOK_RETRIES, change_creds)
            else:
                # In some strange cases the pk_file disappears. So test it and
                # remake basic recipe
                if ctxt_vm['os'] != "windows":
                    success = False
                    try:
                        ssh_client = SSH(ctxt_vm['ip'], ctxt_vm['user'], None,
                                         PK_FILE, ctxt_vm['remote_port'])
                        success = ssh_client.test_connectivity()
                    except:
                        success = False

                    if not success:
                        logger.warn(
                            "Error connecting with SSH using the ansible key with: "
                            + ctxt_vm['ip'] +
                            ". Call the basic playbook again.")
                        basic_playbook = general_conf_data[
                            'conf_dir'] + "/basic_task_all.yml"
                        output_basic = StringIO()
                        ansible_thread = LaunchAnsiblePlaybook(
                            output_basic, basic_playbook, ctxt_vm, 2,
                            inventory_file, None, INTERNAL_PLAYBOOK_RETRIES,
                            True)
                        ansible_thread.join()

                # in the other tasks pk_file can be used
                ansible_thread = LaunchAnsiblePlaybook(
                    logger, playbook, ctxt_vm, 2, inventory_file, PK_FILE,
                    INTERNAL_PLAYBOOK_RETRIES, vm_conf_data['changed_pass'])

            if ansible_thread:
                (task_ok, _) = wait_thread(ansible_thread)
            else:
                task_ok = True
            if not task_ok:
                logger.warn("ERROR executing task %s: (%s/%s)" %
                            (task, num_retries, PLAYBOOK_RETRIES))
            else:
                logger.info('Task %s finished successfully' % task)

        res_data[task] = task_ok
        if not task_ok:
            res_data['OK'] = False
            return res_data

    res_data['OK'] = True

    logger.info('Process finished')
    return res_data
コード例 #38
0
ファイル: main.py プロジェクト: ab-geek/Brute-Force-Master
print 'Script to brute force'

from optparse import OptionParser
import sys
import Utilities
from SSH import SSH

usage = '%s [-h hostname] [-u username] [-p password]' % sys.argv[0]
parser = OptionParser(version='SSH Brute Forcer',usage=usage,add_help_option=False)
parser.add_option("-h",dest="hostname",help="name of host",metavar="HOST")
parser.add_option("-u",dest="username",help="name of user")
parser.add_option("-p",dest="password",help="user password")
parser.add_option("-P","--port",dest="portnumber",help="port number",default=22)

(option,args) = parser.parse_args()

#print Utilities.fileToList('password')
#print Utilities.fileToTuple('targets')

#SSH connection
print option.portnumber
conn = SSH(option.username,option.password,option.hostname,option.portnumber,5)
conn.connect()

コード例 #39
0
ファイル: ctxt_agent.py プロジェクト: buweixiaomi/im
def changeVMCredentials(vm, pk_file):
    if vm['os'] == "windows":
        if 'passwd' in vm and vm['passwd'] and 'new_passwd' in vm and vm['new_passwd']:
            try:
                import winrm
                url = "https://" + vm['ip'] + ":5986"
                s = winrm.Session(url, auth=(vm['user'], vm['passwd']))
                r = s.run_cmd('net', ['user', vm['user'], vm['new_passwd']])

                # this part of the code is never reached ...
                if r.status_code == 0:
                    vm['passwd'] = vm['new_passwd']
                    return True
                else:
                    logger.error(
                        "Error changing password to Windows VM: " + r.std_out)
                    return False
            except winrm.exceptions.UnauthorizedError:
                # if the password is correctly changed the command returns this
                # error
                try:
                    # let's check that the new password works
                    s = winrm.Session(url, auth=(vm['user'], vm['new_passwd']))
                    r = s.run_cmd('echo', ['OK'])
                    if r.status_code == 0:
                        vm['passwd'] = vm['new_passwd']
                        return True
                    else:
                        logger.error(
                            "Error changing password to Windows VM: " + r.std_out)
                        return False
                except:
                    logger.exception(
                        "Error changing password to Windows VM: " + vm['ip'] + ".")
                    return False
            except:
                logger.exception(
                    "Error changing password to Windows VM: " + vm['ip'] + ".")
                return False
    else:  # Linux VMs
        # Check if we must change user credentials in the VM
        if 'passwd' in vm and vm['passwd'] and 'new_passwd' in vm and vm['new_passwd']:
            logger.info("Changing password to VM: " + vm['ip'])
            private_key = vm['private_key']
            if pk_file:
                private_key = pk_file
            try:
                ssh_client = SSH(vm['ip'], vm['user'], vm[
                                 'passwd'], private_key, vm['remote_port'])
                (out, err, code) = ssh_client.execute('sudo bash -c \'echo "' +
                                                      vm['user'] + ':' + vm['new_passwd'] +
                                                      '" | /usr/sbin/chpasswd && echo "OK"\' 2> /dev/null')
            except:
                logger.exception(
                    "Error changing password to VM: " + vm['ip'] + ".")
                return False

            if code == 0:
                vm['passwd'] = vm['new_passwd']
                return True
            else:
                logger.error("Error changing password to VM: " +
                             vm['ip'] + ". " + out + err)
                return False

        if 'new_public_key' in vm and vm['new_public_key'] and 'new_private_key' in vm and vm['new_private_key']:
            logger.info("Changing public key to VM: " + vm['ip'])
            private_key = vm['private_key']
            if pk_file:
                private_key = pk_file
            try:
                ssh_client = SSH(vm['ip'], vm['user'], vm[
                                 'passwd'], private_key, vm['remote_port'])
                (out, err, code) = ssh_client.execute('echo ' +
                                                      vm['new_public_key'] + ' >> .ssh/authorized_keys')
            except:
                logger.exception(
                    "Error changing public key to VM: " + vm['ip'] + ".")
                return False

            if code != 0:
                logger.error("Error changing public key to VM:: " +
                             vm['ip'] + ". " + out + err)
                return False
            else:
                vm['private_key'] = vm['new_private_key']
                return True

    return False
コード例 #40
0
"""SSH Class Test."""

import log

from SSHScreen import SSHScreen
from SSH import SSH

ssh = SSH('127.0.0.1', 'vagrant')
ssh.port = 2222
ssh.key_file_path = '~/.vagrant.d/insecure_private_key'

# stdout, stderr = ssh.run_command('hostname', False)
# print(stdout
#
# ssh.run_command('ls -lha')

remoteScreen = SSHScreen(ssh)

log.header('install')
print(remoteScreen.install())

log.header('installed')
print(remoteScreen.installed())

remoteScreen.kill_all_screens()

log.header('create')
print(remoteScreen.exists())
print(remoteScreen.create())
print(remoteScreen._id)
コード例 #41
0
    def test_SSH(self, popenMock):
        params = SharedState("root", "sshkey_file", "scriptDir", "bootdir",
                             "setupAgentFile", "ambariServer", "centos6",
                             "1.2.1", "8440")
        host_log_mock = MagicMock()
        log = {'text': ""}

        def write_side_effect(text):
            log['text'] = log['text'] + text

        host_log_mock.write.side_effect = write_side_effect
        ssh = SSH(params.user, params.sshkey_file, "dummy-host",
                  "dummy-command", params.bootdir, host_log_mock)
        log_sample = "log_sample"
        error_sample = "error_sample"
        # Successful run
        process = MagicMock()
        popenMock.return_value = process
        process.communicate.return_value = (log_sample, error_sample)
        process.returncode = 0

        retcode = ssh.run()

        self.assertTrue(popenMock.called)
        self.assertTrue(log_sample in log['text'])
        self.assertTrue(error_sample in log['text'])
        command_str = str(popenMock.call_args[0][0])
        self.assertEquals(
            command_str, "['ssh', '-o', 'ConnectTimeOut=60', '-o', "
            "'StrictHostKeyChecking=no', '-o', 'BatchMode=yes', '-tt', '-i', "
            "'sshkey_file', 'root@dummy-host', 'dummy-command']")
        self.assertEqual(retcode, 0)

        log['text'] = ""
        #unsuccessfull run
        process.returncode = 1

        retcode = ssh.run()

        self.assertTrue(log_sample in log['text'])
        self.assertTrue(error_sample in log['text'])
        self.assertEqual(retcode, 1)

        log['text'] = ""
        # unsuccessful run with error message
        process.returncode = 1

        dummy_error_message = "dummy_error_message"
        ssh = SSH(params.user,
                  params.sshkey_file,
                  "dummy-host",
                  "dummy-command",
                  params.bootdir,
                  host_log_mock,
                  errorMessage=dummy_error_message)
        retcode = ssh.run()

        self.assertTrue(log_sample in log['text'])
        self.assertTrue(error_sample in log['text'])
        self.assertTrue(dummy_error_message in log['text'])
        self.assertEqual(retcode, 1)
コード例 #42
0
ファイル: Docker.py プロジェクト: alanpaiva/Python_Basic
 def __init__(self):
     SSH.__init__(self)