示例#1
0
	def instalar(self,name,template):
		with open("Templates/%s.json"%template,"r") as f:
			comandos = json.loads(f.read())
		d = Docker()
		s = SSH() 
		for c in comandos.get("comandos"):
			print s.exec_command(d.execCommand(name,c))
    def _update(self):
        applicationConfig = self.ApplicationConfiguration()
        if(not self.applicationConfig.check()):
            return False

        connectorClass = self.connectors.get(applicationConfig.CONNECTOR)
        if(connectorClass == None):
            return False

        connector = connectorClass.__init__(applicationConfig=applicationConfig)
        if(not connector.check()):
            return False

        ssh = SSH()
        if(not ssh.check()):
            return False

        self.applicationConfig = applicationConfig
        self.taskHandler.applicationConfig = applicationConfig
        self.cloudHandler.applicationConfig = applicationConfig
        self.cloudHandler.connector = connector
        self.processHandler.applicationConfig = applicationConfig
        self.processHandler.ssh = ssh

        return True
 def run(self):
     global cid
     global pending_jobs   #highly thread unsafe, but for now living with it.
     if self.sleep_time > 0:
         self.delay()
     #if not (kill or KILL_DICT[self.path]):
     if self.MASTER_ID != -1:
         #pending_jobs += 1
         pending_jobs.append(self.path)
         self.wait_till_master()
         #pending_jobs -= 1
         pending_jobs.remove(self.path)
     if not (kill or KILL_DICT[self.path]):
         cid.append(self.path)
         #print 'appended!!!!!!',self.path
         #print self.MASTER_ID
         sshOb = SSH(self.host,self.user,self.conf['pass'])
         self.pid,fd,success = sshOb.fork()
         #print '---------------',success
         #print fd
         if success:
             self.parent_processing(fd)
         else:
             cid.remove(self.path)
     DONE_HASH[self.JOB_ID] = True
     dead_jobs.add(self.path)
示例#4
0
 def execute(self, host):
     """Actually execute the command on host."""
     #The command has to be cd `find-path` && gsync && command
     self.client.sync()
     #ssh_command = "cd `ginfo.py -r \"%s\"` && gsync.py . && cd %s && %s" %(self.client.getID(), self.path, self.command)
     ssh_command = 'gsh.py --remote --id \"%s\" --path \"%s\" --command \"%s\"' %(self.client.getID(), self.path, self.command)
     self.ssh = SSH(host, [ ssh_command ]);
     self.ssh.execute()
示例#5
0
 def write_chat_to_channel():
     # Take chat box text and write it to channel and log.
     chat_input = GUI.CHAT_ENTRY.text()
     if (chat_input != ""):
         if(Communicator.ACTIVE_CHANNEL):
             log = Communicator.USER + ": " + chat_input
             SSH.write_to_log(Communicator.ACTIVE_LOG_PATH, log, 
                             Communicator.TCP_HOST, Communicator.TCP_PORT)
             Communicator.update_active_channel()
             GUI.CHAT_ENTRY.setText("")
示例#6
0
	def contratar(self,name,template):
		d = Docker()
		s = SSH()
		s.exec_command(d.createContainer(name))
		#metodo da propria classe
		self.instalar(name,template)
		endereco = s.exec_command(d.getContainerAddress(name))
		endereco = json.loads(endereco)
		print endereco[0].get("NetworkSettings")\
						 .get("Networks")\
						 .get("bridge")\
						 .get("IPAddress")
示例#7
0
    def __extract_tarball_at_node(self, tarball, node):
        logger.console('Extracting tarball to {0} on {1}'.format(
            con.REMOTE_FW_DIR, node['host'])) 
        ssh = SSH()
        ssh.connect(node)

        cmd = 'rm -rf {1}; mkdir {1} ; sudo -Sn tar -zxf {0} -C {1};'.format(
                tarball, con.REMOTE_FW_DIR)
        (ret_code, stdout, stderr) = ssh.exec_command(cmd, timeout=30)
        if 0 != ret_code:
            logger.error('Unpack error: {0}'.format(stderr))
            raise Exception('Failed to unpack {0} at node {1}'.format(
                tarball, node['host']))
示例#8
0
    def __extract_tarball_at_node(self, tarball, node):
        logger.console('Extracting tarball to {0} on {1}'.format(
            con.REMOTE_FW_DIR, node['host']))
        ssh = SSH()
        ssh.connect(node)

        cmd = 'rm -rf {1}; mkdir {1} ; sudo -Sn tar -zxf {0} -C {1};'.format(
            tarball, con.REMOTE_FW_DIR)
        (ret_code, stdout, stderr) = ssh.exec_command(cmd, timeout=30)
        if 0 != ret_code:
            logger.error('Unpack error: {0}'.format(stderr))
            raise Exception('Failed to unpack {0} at node {1}'.format(
                tarball, node['host']))
示例#9
0
class SSHTest(unittest.TestCase):

    port = 1050
    hostname = 'localhost'

    @classmethod
    def setUpClass(cls):
        users = {'testadmin': 'x'}
        MockSSH.startThreadedServer(
            commands,
            prompt="[root@hostname:Active] testadmin # ",
            interface=SSHTest.hostname,
            port=SSHTest.port,
            **users)
        time.sleep(0.5)

    @classmethod
    def tearDownClass(cls):
        print("tearDownClass")
        MockSSH.stopThreadedServer()

    def setUp(self):
        self.that = SSH(SSHTest.hostname, None, None, SSHTest.port)
        self.that.set_missing_host_key_policy(WarningPolicy())

    def tearDown(self):
        self.that.close_connection()

    def testNoError(self):
        '''
        Tests if out exists after running a command.
        '''
        (_, out, _) = self.that.run('ls')
        self.assertIsNotNone(out)

    def testLsReturnValue(self):
        '''
        Checks the return value of ls
        '''
        (_, out, _) = self.that.run('ls')
        self.assertEqual(0, out.channel.recv_exit_status())

    def testLsStringReturned(self):
        '''
        Checks the existance of a string returned by ls.
        '''
        (_, out, _) = self.that.run('ls')
        output = out.read().decode()
        self.assertIsNotNone(output)
        print("\nls returned %s" % output)

    def testEchoStringReturned(self):
        '''
        Tests the reply of the echo command.
        '''
        string = 'The reply'
        (_, out, _) = self.that.run('echo -n ' + string)
        output = out.read().decode()
        print("\necho returned %s" % output)
        self.assertEqual(output, string)
示例#10
0
    def execute_script(self, local_path, node, timeout=10, json_out=True):
        """Copy local_path script to node, execute it and return result.
        
        Returns (rc, stdout, stderr tuple).
        """

        ssh = SSH()
        ssh.connect(node)

        local_basename = os.path.basename(local_path)
        remote_file_path = self.__TMP_DIR + local_basename
        remote_file_out = remote_file_path + ".out"

        ssh.scp(local_path, remote_file_path)

        cmd = "sudo -S {vat} {json} < {input}".format(
            vat=self.__VAT_BIN,
            json="json" if json_out == True else "",
            input=remote_file_path)
        (ret_code, stdout, stderr) = ssh.exec_command(cmd, timeout)
        self._ret_code = ret_code
        self._stdout = stdout
        self._stderr = stderr

        logger.trace("Command '{0}' returned {1}'".format(cmd, self._ret_code))
        logger.trace("stdout: '{0}'".format(self._stdout))
        logger.trace("stderr: '{0}'".format(self._stderr))

        #TODO: download vpp_api_test output file
        self._delete_files(node, remote_file_path, remote_file_out)
示例#11
0
 def _init_ssh(self):
     username, server = self._parse_ssh(self.commands[0])
     client = SSH(server,
                  username,
                  password=self.ssh_password,
                  pkey_path=self.pkey_path,
                  pkey_password=self.pkey_password,
                  screen=self.screen)
     return client
示例#12
0
 def load_local_rosters():
     Communicator.ROSTER = SSH.get_all_rosters(Communicator.TCP_HOST, Communicator.TCP_PORT)
     # Load rosters from database into application.
     for i in range(0, len(Communicator.ROSTER)):
         for j in range(0,len(GUI.CHANNELS)):
             for k in range(0,len(GUI.CHANNELS[j][GUI.ROSTER_GROUP_NAME])):
                 if Communicator.ROSTER[i][0] == GUI.CHANNELS[j][GUI.ROSTER_GROUP_NAME][k]:
                     GUI.CHANNELS[j][GUI.ROSTER].append(Communicator.ROSTER[i])
                 if Communicator.ROSTER[i][2] == GUI.CHANNELS[j][GUI.ROSTER_GROUP_NAME][k]:
                     GUI.CHANNELS[j][GUI.ROSTER].append(Communicator.ROSTER[i])
示例#13
0
  def get_resource_usages(self):
    #query each slash2 compenent for resource usage
    rusages = {}
    for host, type, ctl_path, pid in self.runtime["daemons"]:
      print type
      user = os.getenv("USER")
      ssh = SSH(user, host, '');
      kernel = "".join(ssh.run("uname -s")["out"]).lower()
      if "linux" in kernel:
        output = self.check_status(ssh, type, ctl_path, pid)
      elif "bsd" in kernel:
        output = self.query_ctl_rusage(ssh, type, ctl_path)
      else:
        # do something
        pass
      rusages[host] = output

    return rusages
    sys.exit(1)
示例#14
0
    def __init__(self, username='', password='', repo_name_or_slug=''):
        self.username = username
        self.password = password
        self.repo_slug = repo_name_or_slug.lower().replace(
            r'[^a-z0-9_-]+', '-')
        self.repo_tree = {}

        self.repository = Repository(self)
        self.service = Service(self)
        self.ssh = SSH(self)
        self.issue = Issue(self)
示例#15
0
文件: worker.py 项目: mthxx/Comms
 def update_all_channels(self):
     if(Communicator.ACTIVE_LOG_PATH and
         Communicator.ACTIVE_LOG_PATH != "logs/welcomeMessage.txt"):
         self.delta = SSH.get_all_logs(Communicator.TCP_HOST, Communicator.TCP_PORT)
         if self.delta and self.delta != None:
             Communicator.DELTA.append(self.delta)
             self.channel_notification.emit()
             for i in range(0,len(self.delta)):
                 if self.delta[i] == Communicator.ACTIVE_CHANNEL:
                     self.refresh_signal.emit()
     return
示例#16
0
def main(self, line):
    args = line.split()
    ssh = SSH()
    if len(args) == 0:
        print '''Usage: 
    addhost save_name hostname user [password]
    connect save_name
    connect hostname user password
    '''
        return
    if args[0] == 'addhost':
        ssh.addhost(' '.join(args[1:]))
    elif args[0] == 'connect':
        ssh.connect(' '.join(args[1:]))
    elif args[0] == 'listhost':
        ssh.listhost()
    elif args[0] == 'delhost':
        ssh.delhost(' '.join(args[1:]))
    else:
        print __file__.__doc__
        return
示例#17
0
def main():
    # Input files and variables
    start_time = datetime.now()

    # Devices file and commands source
    devices_file = "/app/src/devices_commands.csv"

    # Format commands and devices on dictionary for outputs
    new_collector = Collector(devices_file)
    new_collector.get_env()
    devices_commands = new_collector.format_devices()
    new_collector.output_json()

    # Send SSH sessions for outputs
    # Number of threads
    number_threads = 10
    # Number of retry
    number_retry = 3
    new_ssh = SSH(devices_commands,number_threads,number_retry)
    new_ssh.run()
    print("Process Collect Files Done: " + str(datetime.now() - start_time))
示例#18
0
    def execute_script(self, local_path, node, timeout=10, json_out=True):
        """Copy local_path script to node, execute it and return result.
        
        Returns (rc, stdout, stderr tuple).
        """

        ssh = SSH()
        ssh.connect(node)

        local_basename = os.path.basename(local_path)
        remote_file_path = self.__TMP_DIR + local_basename
        remote_file_out = remote_file_path + ".out"

        ssh.scp(local_path, remote_file_path)

        cmd = "sudo -S {vat} {json} < {input}".format(vat=self.__VAT_BIN, 
                json="json" if json_out == True else "",
                input=remote_file_path)
        (ret_code, stdout, stderr) = ssh.exec_command(cmd, timeout)
        self._ret_code = ret_code
        self._stdout = stdout
        self._stderr = stderr

        logger.trace("Command '{0}' returned {1}'".format(cmd, self._ret_code))
        logger.trace("stdout: '{0}'".format(self._stdout))
        logger.trace("stderr: '{0}'".format(self._stderr))

        #TODO: download vpp_api_test output file
        self._delete_files(node, remote_file_path, remote_file_out)
示例#19
0
 def __init__(self, name, config=None, config_dir=None, **kwargs):
     self.config = {}
     self.name = name
     self.type = self.PROVIDER_TYPE
     self.connected = False
     if config_dir is None:
         raise Exception("config_dir is a required arg")
     self.config_dir = config_dir
     if config is not None:
         for k, v in config.iteritems():
             self.config[k] = v
     for k, v in kwargs.iteritems():
         self.__dict__[k] = v
     self.ssh = SSH()
示例#20
0
def init_senseguard_database():
    ssh = SSH(**ssh_config)

    for file in INIT_SQL_FILES:
        if os.path.exists(os.path.join(PATH_OF_INIT_SQL_FILES, file)):
            ssh.scp_local_file(file, PATH_OF_INIT_SQL_FILES, '~/')
            ssh.execute_command(
                f"mysql -h{db_config.get('host')} -P{db_config.get('port')} -u{db_config.get('user')} -p{db_config.get('password')} < {file}"
            )
示例#21
0
    def setup_dut(self, node):
        ssh = SSH()
        ssh.connect(node)

        ssh.scp('resources/libraries/bash/dut_setup.sh', '/tmp/dut_setup.sh')
        (ret_code, stdout, stderr) = \
            ssh.exec_command('sudo -Sn bash /tmp/dut_setup.sh')
        logger.trace(stdout)
        if 0 != int(ret_code):
            logger.error('DUT {0} setup script failed: "{1}"'.
                    format(node['host'], stdout + stderr))
            raise Exception('DUT test setup script failed at node {}'.
                    format(node['host']))
示例#22
0
    def __init__(self):
        applicationConfig = self.ApplicationConfiguration()
        if(not applicationConfig.check()):
            sys.exit(1)

        connectorClass = self.connectors.get(applicationConfig.CONNECTOR)
        if(connectorClass == None):
            print applicationConfig.CONNECTOR + ' is not a possible connector class'
            sys.exit(1)

        connector = connectorClass(applicationConfig)
        if(not connector.check()):
            sys.exit(1)

        ssh = SSH()
        if(not ssh.check()):
            sys.exit(1)

        self.applicationConfig = applicationConfig
        self.taskHandler = TaskHandler(applicationConfig=applicationConfig)
        self.cloudHandler = CloudHandler(applicationConfig=applicationConfig, connector=connector)
        self.processHandler = ProcessHandler(applicationConfig=applicationConfig, taskHandler=self.taskHandler, cloudHandler=self.cloudHandler, ssh=ssh)

        self.tokenAuthenticator = TokenAuthenticator(loadTokens())
示例#23
0
    def bruteforce(self, target, port, method, passlist, username):

        parser = Passlist(passlist)
        passwords = parser.get_list()

        if method == "http" or "https":
            attack = Basic_Auth()

        if method == "ssh":
            attack = SSH()

        if method == "ftp":
            attack = FTP()

        attack.brute_force(target, port, username, passwords, method)
示例#24
0
    def __init__(self, username='', password='', repo_name_or_slug=''):
        self.username = username
        self.password = password
        self.repo_slug = repo_name_or_slug
        self.repo_tree = {}
        self.URLS = URLS

        self.repository = Repository(self)
        self.service = Service(self)
        self.ssh = SSH(self)
        self.issue = Issue(self)

        self.access_token = None
        self.access_token_secret = None
        self.consumer_key = None
        self.consumer_secret = None
        self.oauth = None
示例#25
0
class SSHTest(unittest.TestCase):
    '''
    Does an Integration test of the SSH class.
    To succesfully run this test fill in the parameters above with
    values corresponding to an SSH server. This can be any SSH server
    that you can log into. It should even work when the SSH server is local.
    After running please reset all the parameters to None.
    '''

    def setUp(self):
        self.that = SSH(hostname, user, pwd, port)

    def tearDown(self):
        self.that.close_connection()

    def testNoError(self):
        '''
        Tests if out exists after running a command.
        '''
        (_, out, _) = self.that.run('ls')
        self.assertIsNotNone(out)

    def testLsReturnValue(self):
        '''
        Checks the return value of ls
        '''
        (_, out, _) = self.that.run('ls')
        self.assertEqual(0, out.channel.recv_exit_status())

    def testLsStringReturned(self):
        '''
        Checks the existance of a string returned by ls.
        '''
        (_, out, _) = self.that.run('ls')
        output = out.read().decode()
        self.assertIsNotNone(output)
        #print("\nls returned %s" % output)

    def testEchoStringReturned(self):
        '''
        Tests the reply of the echo command.
        '''
        string = 'The reply'
        (_, out, _) = self.that.run('echo -n ' + string)
        output = out.read().decode()
        #print("\necho returned %s" % output)
        self.assertEqual(output, string)
示例#26
0
 def _run_scp(self):
     assert len(self.commands) == 1
     args = self._parse_scp(self.commands[0])
     args.check_fields()
     client = SSH(
         args.server,
         args.username,
         password=self.ssh_password,
         pkey_path=args.pkey,
         pkey_password=self.pkey_password)  # TODO support different keys
     if args.put:
         client.scp_upload(args.file,
                           remote_path=args.remote_path,
                           recursive=args.r)
     else:
         client.scp_download(args.remote_path,
                             recursive=args.r,
                             local_path=args.file)
示例#27
0
def setup_droplet():
    # Create a droplet
    do_key = configparse('DigitalOcean')['digitalocean_api_key']
    do = DO(do_key)
    #do.create_droplet()

    for droplet in do.get_all_droplets(tag_name="vpn-server"):
        ip = droplet.ip_address
    
    print("Waiting for setup of VPN")
    #sleep(35)

    # SSH接続
    path = configparse('SSH')['ssh_secretkey_path']
    
    print(path)
    ssh = SSH(ip,"root",path)
    ssh.connect

    ssh.excute_command("wget https://raw.githubusercontent.com/s151003/openvpn-install/master/openvpn-install.sh && chmod 777 openvpn-install.sh && bash openvpn-install.sh")
    ssh.close()
示例#28
0
    def __copy_tarball_to_node(self, tarball, node):
        logger.console('Copying tarball to {0}'.format(node['host']))
        ssh = SSH()
        ssh.connect(node)

        ssh.scp(tarball, "/tmp/")
示例#29
0
    def shodan_search(self, args):

        shodan = Shodan_Search()

        if shodan.validateapi():
            results = shodan.search(args.shodan)
            response = raw_input(
                'YOU WANT TO TEST SHODAN RESULTS? Y/N: ').upper().strip()

            if response == "Y":

                parser = Passlist(args.passlist)

                for result in results['matches']:

                    passwords = parser.get_list()

                    try:

                        if args.method is None:

                            if result['port'] == 21:
                                method = "ftp"
                                Attack = FTP()

                            if result['port'] == 22:
                                method = "ssh"
                                Attack = SSH()

                            if result['port'] == 443:
                                method = "https"
                                Attack = Basic_Auth()

                            else:
                                args.method = "http"
                                Attack = Basic_Auth()

                        else:

                            if args.method == "http":
                                method = "http"
                                Attack = Basic_Auth()

                            if args.method == "https":
                                method = "https"
                                Attack = Basic_Auth

                            if args.method == "ftp":
                                method = "ftp"
                                Attack = FTP()

                            if args.method == "ssh":
                                method = "ssh"
                                Attack = SSH()

                        Attack.brute_force(result['ip_str'], result['port'],
                                           args.username, passwords, method)

                    except:
                        pass

            else:
                sys.exit()

        else:
            sys.exit()
示例#30
0
class GSH:
    "The main class.  First you build it, then you tweak it, then you execute it."

    def __init__(self, command, path=os.getcwd()):
        self.command = command;
        path = os.path.realpath(os.path.abspath(path))
        self.client = GitFSClient.getClientByPath(path)
        self.path = self.client.makeRootRelative(path)
        if self.path is None or self.path == '':
            self.path = '.'

    def execute(self, host):
        """Actually execute the command on host."""
        #The command has to be cd `find-path` && gsync && command
        self.client.sync()
        #ssh_command = "cd `ginfo.py -r \"%s\"` && gsync.py . && cd %s && %s" %(self.client.getID(), self.path, self.command)
        ssh_command = 'gsh.py --remote --id \"%s\" --path \"%s\" --command \"%s\"' %(self.client.getID(), self.path, self.command)
        self.ssh = SSH(host, [ ssh_command ]);
        self.ssh.execute()

    def setNonBlocking(self):
        fcntl.fcntl(self.stderr(), fcntl.F_SETFL, os.O_NDELAY)
        fcntl.fcntl(self.stdout(), fcntl.F_SETFL, os.O_NDELAY)
        fcntl.fcntl(self.stdin(), fcntl.F_SETFL, os.O_NDELAY)

    def pollInfo(self):
        """returns a dict of names: (fileno, read, write, error, ...) tuples.
        names are only used to pass back into the handler for read/write/errors.
        Anything after the 4th entry in the tuple is ignored.  The whole return from
        this function is passed back in, so extra information can be stashed all over the
        place.
        """
        return { 'stdout': [ self.ssh.stdin(), False, len(self.out_buffer) > 0, True ],
                'stdin' : [ self.ssh.stdout(),  len(self.in_buffer) < self.buffer_max, False, True ],
                'stderr': [ self.ssh.stderr(),  len(self.err_buffer) < self.buffer_max, False, True ]
                }

    def pollHit(self, name, res):
        if name == 'stdout':
            self.readStdout()
        elif name == 'stdin':
            self.writeStdin()
        elif name == 'stderr':
            self.readStderr()

    def _read(self, file, size):
        try:
            buff = file.read(size)
        except OS.IOError as ioe:
            if ioe.errno != errno.EAGAIN and ioe.errno != errno.EWOULDBLOCK:
                raise ioe
            buff = ''
        return buff
            
    def _write(self, file, buffer):
        try:
            ret = file.write(buffer)
        except OS.IOError as ioe:
            if ioe.errno != errno.EAGAIN and ioe.errno != errno.EWOULDBLOCK:
                raise ioe
            ret = 0
        return ret

    def readStdin(self):
        buff = self._read(self.stdin(), self.max_in_buff - len(self.in_buffer) )
        self.in_buffer.append(buff)
        for f in self.stdin_call_backs:
            f(self)

    def readStdout(self):
        buff = self._read(self.stdout(), self.max_out_buff - len(self.out_buffer) )
        self.out_buffer.append(buff)
        for f in self.stdout_call_backs:
            f(self)

    def readStderr(self):
        buff = self._read(self.stderr(), self.max_err_buff - len(self.err_buffer) )
        self.err_buffer.append(buff)
        for f in self.stderr_call_backs:
            f(self)

    def writeStdIn(self):
        if len(self.in_buff) > 0:
            w = self._write(self.stdin(), self.in_buff)
            if w > 0:
                self.in_buff = self.in_buff[w:]
                for f in self.stdin_call_backs:
                    f(self)

    def stdout(self):
        if self.ssh is None:
            return None
        return self.ssh.stdout()

    def stderr(self):
        if self.ssh is None:
            return None
        return self.ssh.stderr()

    def stderr(self):
        if self.ssh is None:
            return None
        return self.ssh.stderr()

    def read(self):
        return self.stdout().read()

    def write(self, buff):
        return self.stdin().write(buff)

    def readerr(self):
        return self.stderr().read()

    def displayAndWait(self):
        if self.ssh is not None:
            self.ssh.displayAndWait()
示例#31
0
	def listar_servicos(self):
		d = Docker()
		s = SSH()
		print s.exec_command(d.listContainer())
示例#32
0
 def _delete_files(self, node, *files):
     ssh = SSH()
     ssh.connect(node)
     files = " ".join([str(x) for x in files])
     ssh.exec_command("rm {0}".format(files))
示例#33
0
    def __copy_tarball_to_node(self, tarball, node):
        logger.console('Copying tarball to {0}'.format(node['host']))
        ssh = SSH()
        ssh.connect(node)

        ssh.scp(tarball, "/tmp/")
示例#34
0
文件: views.py 项目: teazj/wsshsftp
 def put_client(self):
     ssh = SSH(self)
     self.clients[self._id()] = ssh
示例#35
0
	def __init__(self):
		SSH.__init__(self)
		self.log_file = "docker.log"
		self.image = "ubuntu"
示例#36
0
    Session = sessionmaker(bind=engine)
    session = Session()

    qry_all_machines = session.query(Machine)

    for machine in qry_all_machines:

        data_e_hora_atuais = datetime.now()

        ref_time = RefTime(time_ref=data_e_hora_atuais, machine_id=machine.id)
        session.add(ref_time)
        session.commit()

        try:
            con_ssh = SSH(hostname=machine.hostname, username=machine.username)

            ca = ConnectionActive(connected='YES', ref_time_id=ref_time.id)
            session.add(ca)
            session.commit()

            disk_usage = con_ssh.cmd_disk_usage()
            for disk in disk_usage:
                du = DiskUsage(filesystem=disk['filesystem'],
                               type=disk['type'],
                               size=disk['size'],
                               used=disk['used'],
                               mounted_on=disk['mounted_on'],
                               available=disk['available'],
                               use_percent=disk['use_percent'],
                               ref_time_id=ref_time.id)
示例#37
0
 def setUp(self):
     self.that = SSH(SSHTest.hostname, None, None, SSHTest.port)
     self.that.set_missing_host_key_policy(WarningPolicy())
示例#38
0
def test_services(service):
    ssh = SSH("localhost")
    ssh.sudo(f"systemctl restart {service}")
    is_active = ssh.sudo(f"systemctl is-active {service}")
    assert is_active["out"].rstrip() == "active"
    assert requests.get(url).status_code == 200
示例#39
0
    def connect(self):
        try:
            self.accept()
            query_string = self.scope['query_string']
            connect_argv = QueryDict(query_string=query_string,
                                     encoding='utf-8')
            server_id = connect_argv.get('server_id')
            user = connect_argv.get('user')
            width = connect_argv.get('width')
            height = connect_argv.get('height')

            width = int(width)
            height = int(height)

            connect_info = get_object_or_404(models.Server, id=server_id)

            host = connect_info.alias
            port = connect_info.ssh_port
            # auth = ''
            # pkey = ''

            # connect_info.delete()

            if user == str("root"):
                #     # password = base64.b64decode(pwd).decode('utf-8')
                password = connect_info.ssh_user_root_password
            else:
                password = connect_info.ssh_user_other_password

            self.ssh = SSH(websocker=self, message=self.message)
            # self.ssh = SSH(websocker=self)

            self.ssh.connect(host=host,
                             user=user,
                             password=password,
                             port=port,
                             pty_width=width,
                             pty_height=height)

            # if auth == 'key':
            #     pkey = pkey
            #     obj = StringIO()
            #     obj.write(pkey)
            #     obj.flush()
            #     obj.seek(0)
            #     self.pkey = obj
            #
            #     self.ssh.connect(
            #         host=host,
            #         user=user,
            #         password=password,
            #         pkey=self.pkey,
            #         port=port,
            #         pty_width=width,
            #         pty_height=height
            #     )
            # else:
            #     self.ssh.connect(
            #         host=host,
            #         user=user,
            #         password=password,
            #         port=port,
            #         pty_width=width,
            #         pty_height=height
            #     )
        except Exception as e:
            self.message['status'] = 1
            self.message['message'] = str(e)
            message = json.dumps(self.message)
            self.send(message)
            self.close()
示例#40
0
 def _delete_files(self, node, *files):
     ssh = SSH()
     ssh.connect(node)
     files = " ".join([str(x) for x in files])
     ssh.exec_command("rm {0}".format(files))
示例#41
0
 def _get_ssh(self):
     return SSH(host=self.ceph_host,
                user=self.ceph_user,
                password=self.ceph_password,
                key_file=self.ceph_key_file)
示例#42
0
	def cancelar(self,name):
		d = Docker()
		s = SSH()
		print s.exec_command(d.removeContainer(name))
示例#43
0
            raise

        except WorkerDied, e:
            self.status("worker died (%s) # %s" % (e, command), True)
            raise self.Error(e)

        except CommandTimeout:
            self.status("timeout # %s" % command, True)
            exitcode = None

        else:
            if ssh_command.exitcode == 255 and re.match(
                    r'^ssh: connect to host.*:.*$', ssh_command.output):
                self.status("worker unreachable # %s" % command)
                self.logs.worker.write("%s\n" % ssh_command.output)
                raise self.Error(SSH.Error(ssh_command.output))

            self.status("exit %d # %s" % (ssh_command.exitcode, command), True)
            exitcode = ssh_command.exitcode

        finally:
            ssh_command.terminate()

        if ssh_command.exitcode != 0:
            self.strike += 1
            if self.strikes and self.strike >= self.strikes:
                self.status("terminating worker after %d strikes" %
                            self.strikes)
                raise self.Error

            if job.retry < job.retry_limit:
示例#44
0
 def populate_channel(log_path):
     # Populate the channel with both logs and rosters
     log = SSH.get_active_log(Communicator.SSH_CONNECTION,log_path, Communicator.TCP_HOST, Communicator.TCP_PORT)
     Communicator.write_to_channel(log_path,log)
     Communicator.write_to_roster()
示例#45
0
    def __init__(self,
                 session_logs,
                 taskconf,
                 sshkey,
                 ipaddress=None,
                 destroy=None,
                 event_stop=None,
                 launchq=None):

        self.pid = os.getpid()

        if event_stop:
            signal.signal(signal.SIGINT, signal.SIG_IGN)

        self.event_stop = event_stop

        self.logs = session_logs
        self.sshkey = sshkey

        self.strikes = taskconf.strikes
        self.strike = 0

        self.timeout = taskconf.timeout
        self.cleanup_command = taskconf.post
        self.user = taskconf.user

        self.ipaddress = ipaddress
        self.instanceid = None

        self.hub = None
        self.ssh = None

        if destroy is None:
            if ipaddress:
                destroy = False
            else:
                destroy = True
        self.destroy = destroy

        if not ipaddress:
            if not taskconf.hub_apikey:
                raise self.Error(
                    "can't auto launch a worker without a Hub API KEY")
            self.hub = Hub(taskconf.hub_apikey)

            if launchq:
                with sighandle.sigignore(signal.SIGINT, signal.SIGTERM):
                    instance = launchq.get()
            else:

                class Bool:
                    value = False

                stopped = Bool()

                def handler(s, f):
                    stopped.value = True

                with sighandle.sighandle(handler, signal.SIGINT,
                                         signal.SIGTERM):

                    def callback():
                        return not stopped.value

                    instance = list(
                        self.hub.launch(1, VerboseLog(session_logs.manager),
                                        callback, **taskconf.ec2_opts))[0]

            if not instance or (event_stop and event_stop.is_set()):
                raise self.Terminated

            self.ipaddress, self.instanceid = instance

            self.status("launched worker %s" % self.instanceid)

        else:
            self.status("using existing worker")

        self.handle_stop = self._stop_handler(event_stop)

        try:
            self.ssh = SSH(self.ipaddress,
                           identity_file=self.sshkey.path,
                           login_name=taskconf.user,
                           callback=self.handle_stop)
        except SSH.Error, e:
            self.status("unreachable via ssh: " + str(e))
            traceback.print_exc(file=self.logs.worker)

            raise self.Error(e)
示例#46
0
from ssh import SSH
from helper import *

if __name__ == '__main__':

    ip = input("Enter ip: ").strip()
    mask = input("Enter mask: ").strip()
    row_id = input("Enter row id: ").strip()

    # Store credentials in 'auth_data' and script won't ask you about them.
    # login, password = auth_data(ip)
    login, password = auth_data_alt(ip)

    with SSH(ip, login, password) as ssh:
        path = ssh.path_to_logfile(mask)
        file = ssh.read_logfile(path)
        rows = find_result(file, row_id)
        print_log(rows)
示例#47
0
 /_/    \_\__,_|\__\___/|_|  |_|\__, |\__,_|_|  \__,_|
                                 __/ |                
                                |___/  
          _)                              (_
         _) \ /\%/\  /\%/\  /\%/\  /\%/\ / (_
        _)  \\(0 0)  (0 0)  (0 0)  (0 0)//  (_
        )_ -- \(oo)   (oo)   (oo)  (oo)/-- _(
         )_ / /  \_,__/ \__,__/ \_,__/  \ \ _(
          )_ /   --;-- --;- --;-- --;--  \ _( 
       *.   (      ))   ()   ((     ()    )    .*
         '...(___)z z(__)z(__)z(__)z z(__)....'  

"""

exploits = {
    'ssh': SSH(),
    'http': HTTP(),
    'postgres': postgresql(),
    'ldap': LDAP()
}

def read_lines(filename):
    with open(filename, 'r') as f:
        lines = f.read_lines()
    return lines

def main():
    import argparse
    parser = argparse.ArgumentParser(description="Automate Hydra attacks against a specified network range.")
    parser.add_argument("-i", "--host_ips", metavar="<i>", type=str,
                        help="IP address range to search", dest='host_ips')
示例#48
0
 def setUp(self):
     self.that = SSH(hostname, user, pwd, port)
示例#49
0
文件: worker.py 项目: mthxx/Comms
 def get_channels(self):
     Communicator.CHANNEL_LIST = SSH.get_channels(Communicator.TCP_HOST, Communicator.TCP_PORT)
     self.channels_received.emit()
示例#50
0
文件: worker.py 项目: mthxx/Comms
 def update_online_users(self): 
     self.users = SSH.whos_online(Communicator.TCP_HOST, Communicator.TCP_PORT, Communicator.ONLINE_USERS, Communicator.USER)
     if self.users != Communicator.ONLINE_USERS and self.users != None:
         Communicator.ONLINE_USERS = self.users
         self.update_online_list.emit()
     return
示例#51
0
class WebSSH(WebsocketConsumer):
    message = {'status': 0, 'message': None}
    """
    status:
        0: ssh 连接正常, websocket 正常
        1: 发生未知错误, 关闭 ssh 和 websocket 连接
    message:
        status 为 1 时, message 为具体的错误信息
        status 为 0 时, message 为 ssh 返回的数据, 前端页面将获取 ssh 返回的数据并写入终端页面
    """

    # status = {'code': 1001, 'error': ''}

    def connect(self):
        try:
            self.accept()
            query_string = self.scope['query_string']
            connect_argv = QueryDict(query_string=query_string,
                                     encoding='utf-8')
            server_id = connect_argv.get('server_id')
            user = connect_argv.get('user')
            width = connect_argv.get('width')
            height = connect_argv.get('height')

            width = int(width)
            height = int(height)

            connect_info = get_object_or_404(models.Server, id=server_id)

            host = connect_info.alias
            port = connect_info.ssh_port
            # auth = ''
            # pkey = ''

            # connect_info.delete()

            if user == str("root"):
                #     # password = base64.b64decode(pwd).decode('utf-8')
                password = connect_info.ssh_user_root_password
            else:
                password = connect_info.ssh_user_other_password

            self.ssh = SSH(websocker=self, message=self.message)
            # self.ssh = SSH(websocker=self)

            self.ssh.connect(host=host,
                             user=user,
                             password=password,
                             port=port,
                             pty_width=width,
                             pty_height=height)

            # if auth == 'key':
            #     pkey = pkey
            #     obj = StringIO()
            #     obj.write(pkey)
            #     obj.flush()
            #     obj.seek(0)
            #     self.pkey = obj
            #
            #     self.ssh.connect(
            #         host=host,
            #         user=user,
            #         password=password,
            #         pkey=self.pkey,
            #         port=port,
            #         pty_width=width,
            #         pty_height=height
            #     )
            # else:
            #     self.ssh.connect(
            #         host=host,
            #         user=user,
            #         password=password,
            #         port=port,
            #         pty_width=width,
            #         pty_height=height
            #     )
        except Exception as e:
            self.message['status'] = 1
            self.message['message'] = str(e)
            message = json.dumps(self.message)
            self.send(message)
            self.close()

    def disconnect(self, close_code):
        try:
            self.ssh.close()
        except:
            pass

    def receive(self, text_data=None, bytes_data=None):
        data = json.loads(text_data)
        if type(data) == dict:
            status = data['status']
            if status == 0:
                data = data['data']
                self.ssh.shell(data)
            else:
                cols = data['cols']
                rows = data['rows']
                self.ssh.resize_pty(cols=cols, rows=rows)