Esempio n. 1
0
def get_templates(ip):

    '''
    This function checks if the template for the orginal start-up config file exists for each of the 3 routers. If not, it
    downloads and saves the original start-up config file from each of the routers and creates a reference template for all 3.
    If it exists, it downloads and saves the current start-up config file and creates the template from it thereafter. Now it
    compares this new template with the reference template.Additionally, the original start-up and the crrent start-up config
    files are also compared.
    '''


    temp_file= "/home/netman/DB/"+ip+"template_final"

    if not os.path.exists(temp_file):
        print "CREATING TEMPLATES"
        connection = tftpy.TftpClient(ip, 69)
        connection.download('/startup-config',"/home/netman/DB/"+ip+"template")
        make_templates("/home/netman/DB/"+ip+"template",0)
    else:
        file_name="/home/netman/DB/"+ip+"current_template"
        #'fine_name' and 'file_name_compare' are the same.
        connection = tftpy.TftpClient(ip, 69)
        connection.download('/startup-config',file_name)
        make_templates(file_name,1)
        compare_templates(file_name+"_compare",temp_file,ip)
        compare_config(file_name,"/home/netman/DB/"+ip+"template",ip)
Esempio n. 2
0
 def do_flash(self, args):
     strs = args.split()
     if len(strs) == 2 and strs[0].isdigit() and strs[1].isdigit():
         ip_start = int(strs[0])
         ip_end = int(strs[1])
         if ip_end > ip_start and ip_start in range(
                 0, 255) and ip_end in range(0, 255):
             total_cnt = ip_end - ip_start
             error_cnt = 0
             for index in range(ip_start, ip_end):
                 ip = "192.168.1." + str(index)
                 try:
                     client = tftpy.TftpClient(ip, 69)
                     client.upload('Ethernet_app.bin', 'Ethernet_app.bin')
                     sys.stdout.write("  OK\n")
                 except Exception:
                     set_color(FOREGROUND_RED)
                     sys.stdout.write("    FAIL\n")
                     sys.stdout.flush()
                     reset_color()
                     error_cnt += 1
             print("Flash %d Module, %d Success, %d Failed" %
                   (total_cnt, total_cnt - error_cnt, error_cnt))
         else:
             print("IP index illegal")
     else:
         print("Syntax error")
Esempio n. 3
0
    def makeTftpRetrieval(self):
        """
        """
        progresshook = Progress(self).progresshook

        if CONFIG.has_option('honeypot', 'download_limit_size'):
            self.limit_size = CONFIG.getint('honeypot', 'download_limit_size')

        self.artifactFile = Artifact(self.file_to_get)

        tclient = None
        url = ''

        try:
            tclient = tftpy.TftpClient(self.hostname, int(self.port))

            # tftpy can't handle unicode string as filename
            # so we have to convert unicode type to str type
            tclient.download(str(self.file_to_get), self.artifactFile,
                             progresshook)

            url = 'tftp://%s/%s' % (self.hostname, self.file_to_get.strip('/'))

            self.file_to_get = self.fs.resolve_path(self.file_to_get,
                                                    self.protocol.cwd)

            if hasattr(tclient.context, 'metrics'):
                self.fs.mkfile(self.file_to_get, 0, 0,
                               tclient.context.metrics.bytes, 33188)
            else:
                self.fs.mkfile(self.file_to_get, 0, 0, 0, 33188)

        except tftpy.TftpException:
            if tclient and tclient.context and not tclient.context.fileobj.closed:
                tclient.context.fileobj.close()

        if url:

            # log to cowrie.log
            log.msg(
                format=
                'Downloaded URL (%(url)s) with SHA-256 %(shasum)s to %(outfile)s',
                url=url,
                outfile=self.artifactFile.shasumFilename,
                shasum=self.artifactFile.shasum)

            self.protocol.logDispatch(
                eventid='cowrie.session.file_download',
                format=
                'Downloaded URL (%(url)s) with SHA-256 %(shasum)s to %(outfile)s',
                url=url,
                outfile=self.artifactFile.shasumFilename,
                shasum=self.artifactFile.shasum,
                destfile=self.file_to_get)

            # Update the honeyfs to point to downloaded file
            self.fs.update_realfile(self.fs.getfile(self.file_to_get),
                                    self.artifactFile.shasumFilename)
            self.fs.chown(self.file_to_get, self.protocol.user.uid,
                          self.protocol.user.gid)
    def tftp_file(self, host='', remote_file='', local_file='', mode=None):
        '''
        tftp_file to get file from remote tftp server.
        get eg:
        | tftp_file | 172.16.1.100 | test1.iso | c:\\ftp\\test1.iso | get |
        get test1.iso freom tftp server 172.16.1.100 save local file c:\ftp\test1.iso
        
        put eg:
        | tftp_file | 172.16.1.100 | test1.iso | c:\\ftp\\test1.iso | put |
        put local file c:\ftp\test1.iso to tftp server 172.16.1.100 named test1.iso
        '''
        print("run keyword:%s host=%s" %
              (sys._getframe().f_code.co_name, host))
        host = _unicode_to_utf(host)
        remote_file = _unicode_to_utf(remote_file)
        local_file = _unicode_to_utf(local_file)
        mode = _unicode_to_utf(mode)

        client = tftpy.TftpClient(host, 69)
        if mode == None or mode == 'get' or mode == 'Get' or mode == 'None':
            client.download(remote_file, local_file)
        elif mode == 'put' or mode == 'Put':
            client.upload(remote_file, local_file)
        else:
            raise ExpectError("action %s error" % mode)
Esempio n. 5
0
    def clientServerUploadOptions(self,
                                  options,
                                  input=None,
                                  transmitname=None,
                                  server_kwargs=None):
        """Fire up a client and a server and do an upload."""
        root = '/tmp'
        home = os.path.dirname(os.path.abspath(__file__))
        filename = '640KBFILE'
        input_path = os.path.join(home, filename)
        if not input:
            input = input_path
        if transmitname:
            filename = transmitname
        server_kwargs = server_kwargs or {}
        server = tftpy.TftpServer(root, **server_kwargs)
        client = tftpy.TftpClient('localhost',
                                  20001,
                                  options)
        # Fork a server and run the client in this process.
        child_pid = os.fork()
        if child_pid:
            # parent - let the server start
            try:
                time.sleep(1)
                client.upload(filename,
                              input)
            finally:
                os.kill(child_pid, 15)
                os.waitpid(child_pid, 0)

        else:
            server.listen('localhost', 20001)
Esempio n. 6
0
def get_files_list(a_ip: str) -> Optional[List[str]]:
    tftp_client = tftpy.TftpClient(a_ip, 69)
    try:
        tftp_client.download("ls.txt", __files_list_filename, timeout=1)
    except tftpy.TftpTimeout:
        logging.error(Text.get("get_files_list_err"))
        if os.path.isfile(__files_list_filename):
            tftp_client.context.end()
            os.remove(__files_list_filename)
        return None
    except Exception:
        if os.path.isfile(__files_list_filename):
            tftp_client.context.end()
            os.remove(__files_list_filename)
        raise
    else:
        with open(__files_list_filename, encoding='cp1251') as files_list_file:
            files_list = []
            for filename in files_list_file:
                for word in __exclude_words:
                    if word in filename:
                        break
                else:
                    files_list.append(filename.strip())
        os.remove(__files_list_filename)

    return files_list
Esempio n. 7
0
    def run(self):  # send update signal to gui window periodically
        num_transmission_errors = 0

        while True:
            while self.pause:  # if pausing, or not yet initialized
                time.sleep(0.2)
            if self.stop: break  # if told to stop
            start_time = time.time()
            # create client object for transfer
            client = tftpy.TftpClient(self.ip_address,
                                      self.port_num,
                                      options={'blksize': DEFAULT_BLK_SIZE})
            try:
                # try to download 'server_frame_buffer/frame.png' from server
                client.download(SERVER_DIR + "/" + FRAME_FILE,
                                CLIENT_DIR + "/" + FRAME_FILE,
                                timeout=MAX_WAIT_TIME)
                # set the path to the new frame in the parent
                self.parent.current_frame_file = CLIENT_DIR + "/" + FRAME_FILE
                # tell the parent to update with the new frame
                self.update_gui.emit()
            except:
                print("Transmission Error")
                num_transmission_errors += 1
            print("Transfer time: %0.4f" % (time.time() - start_time))
            time.sleep(REFRESH_AFTER)
Esempio n. 8
0
File: test.py Progetto: weyou/tftpy
    def testServerDownloadWithStopNotNow(self, output='/tmp/out'):
        log.debug("===> Running testcase testServerDownloadWithStopNotNow")
        root = os.path.dirname(os.path.abspath(__file__))
        server = tftpy.TftpServer(root)
        client = tftpy.TftpClient('localhost', 20001, {})
        # Fork a server and run the client in this process.
        child_pid = os.fork()
        if child_pid:
            # parent - let the server start
            stopped_early = False
            try:
                time.sleep(1)
                client.download('640KBFILE', output)
            except:
                log.warn("client threw exception as expected")
                stopped_early = True

            finally:
                os.kill(child_pid, 15)
                os.waitpid(child_pid, 0)

            self.assertTrue(stopped_early == False)

        else:
            import signal

            def handlealarm(signum, frame):
                server.stop(now=False)

            signal.signal(signal.SIGALRM, handlealarm)
            signal.alarm(2)
            try:
                server.listen('localhost', 20001)
            except Exception, err:
                self.assertTrue(False, "Server should not exit early")
Esempio n. 9
0
def getTFTPFile(router):
    fileName = router[FILE_NAME] #Obtiene el nombre del archivo de configuración del router mediante su llave filename
    print('Obteniendo archivo %s desde el servidor TFTP [%s:%d]' % (fileName, TFTP_SERVER_ADDRESS, TFTP_PORT))
    client = tftpy.TftpClient(TFTP_SERVER_ADDRESS, TFTP_PORT) 
    client.download(fileName, fileName)
    print('Archivo %s obtenido exitosamente!' % fileName)
    return
Esempio n. 10
0
    def send_authorize_information(cls, device_ip, username, password, cli,
                                   authz_info, tftp_server, tftp_loc, uuid):
        s = slr("", "", "")
        client = tftpy.TftpClient(tftp_server, 69)
        file_name = device_ip + secrets.token_hex(5) + extension
        dest_file = dest_dir + file_name

        try:
            f = open(dest_file, "w+")
            print(authz_info)
            f.write(authz_info)
            f.close()
            client.upload(tftp_loc + file_name, dest_file)
            cli.append("lic smart reservation install file tftp://" +
                       tftp_server + "/" + tftp_loc + file_name)
            print(cli)
            slrauthzswitch.config_commands(device_ip, username, password, cli)
            s.update_status(slr_req_tbl, uuid, device_ip, s_done, step)
        except Exception as e:
            print(e)
            s.update_status(slr_req_tbl, uuid, device_ip,
                            str(e).split(":")[0], step)

        rows = s.find_by_step_status(slr_req_tbl, uuid, s_start, step)
        if (len(rows) == 0):
            response_update = {}
            response_update['status'] = resp_status_complete
            TokensModel.update(uuid, response_update, "upload_info_store")
        del (s)
Esempio n. 11
0
    async def PostFile(self, src, destname):
        self.inx = 0
        self.pktsize = os.path.getsize(src) / 1024

        def hook(packet):
            self.inx += 1
            self.confnodesroot.ShowPLCProgress(status=(_('Downloading')), progress=self.inx * 100 / self.pktsize)

        self.TransactionLock.acquire()
        cnt = 0
        await self.HandleSerialTransaction(SETRTCTransaction())
        await self.HandleSerialTransaction(TFTP_PLCBINTransaction())
        while True:
            try:
                self.inx = 0
                t = tftpy.TftpClient(self.ip, options={'blksize': 512})
                res = True
                t.upload(destname, src, packethook=hook, timeout=2)
                break
            except Exception as ex:
                if self.confnodesroot:
                    self.confnodesroot.logger.write_error(str(ex))
                    self.confnodesroot.logger.write_error("正在重试 %d / 10..." % (cnt + 1))
                    # self.confnodesroot.logger.write_error(traceback.format_exc())
                res = None
            cnt += 1
            if cnt == 10: break
        self.TransactionLock.release()
        if self.confnodesroot:
            self.confnodesroot.HidePLCProgress()
        return res
Esempio n. 12
0
    def testServerDownloadWithPrivDropPrivilegedPortUseridOnly(
            self, output='/tmp/out'):
        """Basic test of privilege dropping- the test must be started as root"""
        log.debug(
            "===> Running testcase testServerDownloadWithPrivDropPrivilegedPortUseridOnly"
        )
        root = os.path.dirname(os.path.abspath(__file__))

        server = tftpy.TftpServer(root,
                                  drop_privileges=(VALID_UID, None),
                                  paranoid=False)
        server_thread = threading.Thread(target=server.listen,
                                         kwargs={
                                             'listenip': 'localhost',
                                             'listenport': 69
                                         })
        server_thread.start()

        try:
            server.is_running.wait()
            client = tftpy.TftpClient('localhost', server.listenport, {})
            time.sleep(1)
            client.download('640KBFILE', output)
        finally:
            server.stop(now=False)
            server_thread.join()
            # Remove the file and re-escalate privileges so that they can be dropped
            # again in other privilege dropping test cases. The file must be unlinked
            # because privileges may be dropped to a user that does not have permission
            # to read or write it
            os.unlink(output)
            os.setreuid(ROOT_UID, ROOT_UID)
            os.setregid(ROOT_GID, ROOT_GID)
Esempio n. 13
0
    def __init__(self, **kwargs):
        """
        Initialized Tapcp FPGA object

        :param host: IP Address of the targeted Board
        """
        try:
            import tftpy
            TFTPY.setLevel(logging.CRITICAL)
        except ImportError:
            raise ImportError(
                'You need to install tftpy to use TapcpTransport')

        Transport.__init__(self, **kwargs)
        set_log_level(logging.ERROR)
        self.t = tftpy.TftpClient(kwargs['host'], 69)

        try:
            self.parent = kwargs['parent_fpga']
            self.logger = self.parent.logger
        except KeyError:
            errmsg = 'parent_fpga argument not supplied when creating tapcp device'
            raise RuntimeError(errmsg)

        new_connection_msg = '*** NEW CONNECTION MADE TO {} ***'.format(
            self.host)
        self.logger.info(new_connection_msg)
        self.timeout = kwargs.get('timeout', 3)
        self.server_timeout = 0.1  # Microblaze timeout period. So that if a command fails we can wait for the microblaze to terminate the connection before retrying
        self.retries = kwargs.get(
            'retries', 8
        )  # These are retries of a complete transaction (each of which has it's ofw TFTP retries).
Esempio n. 14
0
def tftp_download(host, rfile, lfile):
    try:
        client = tftpy.TftpClient(host, 69)
        client.download(rfile, lfile)
        return True
    except Exception as e:
        return False
Esempio n. 15
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            host=dict(type='str', required=True),
            filename=dict(type='str', required=True),
            output=dict(type='str', required=True),
        )
    )

    if not HAS_TFTPY:
        module.fail_json(
            msg = missing_required_lib("tftpy"),
            exception = TFTPY_IMP_ERR
        )

    result = {'changed': False}

    host = module.params['host']
    filename = module.params['filename']
    output = module.params['output']

    client = tftpy.TftpClient(host)
    client.download(filename, output)

    module.exit_json(**result)
Esempio n. 16
0
 def tftp_test(self):
     try:
         client = tftpy.TftpClient(self.target, self.port)
         res = client.download(self.filename, 'tftpout', timeout=3)
         self.success = self.should_pass
     except:
         self.success = not self.should_pass
Esempio n. 17
0
 def TFTP_query(self):
     client=tftpy.TftpClient(self.dest_address, self.dest_port)
     try:
         client.download('file.txt', '/home/file.txt', timeout=self.time_out)
         raise tftpy.TftpContexts
     except tftpy.TftpTimeout:
         self.TFTP_service=False
     except:
         self.TFTP_service=True
Esempio n. 18
0
def UploadToTFTP(ip, port):
    try:
        TFTPclient = tftpy.TftpClient(ip, port)
        TFTPclient.upload("database.sqlite",
                          "database.sqlite",
                          packethook=None,
                          timeout=5)
    except:
        print("Failed to upload to TFTP server")
Esempio n. 19
0
    def makeTftpRetrieval(self):
        progresshook = Progress(self).progresshook

        self.artifactFile = Artifact(self.file_to_get)

        tclient = None
        url = ""

        try:
            tclient = tftpy.TftpClient(self.hostname, int(self.port))

            # tftpy can't handle unicode string as filename
            # so we have to convert unicode type to str type
            tclient.download(str(self.file_to_get), self.artifactFile,
                             progresshook)

            url = "tftp://{}/{}".format(self.hostname,
                                        self.file_to_get.strip("/"))

            self.file_to_get = self.fs.resolve_path(self.file_to_get,
                                                    self.protocol.cwd)

            if hasattr(tclient.context, "metrics"):
                self.fs.mkfile(self.file_to_get, 0, 0,
                               tclient.context.metrics.bytes, 33188)
            else:
                self.fs.mkfile(self.file_to_get, 0, 0, 0, 33188)

        except tftpy.TftpException:
            if tclient and tclient.context and not tclient.context.fileobj.closed:
                tclient.context.fileobj.close()

        if url:
            # log to cowrie.log
            log.msg(
                format=
                "Downloaded URL (%(url)s) with SHA-256 %(shasum)s to %(outfile)s",
                url=url,
                outfile=self.artifactFile.shasumFilename,
                shasum=self.artifactFile.shasum,
            )

            self.protocol.logDispatch(
                eventid="cowrie.session.file_download",
                format=
                "Downloaded URL (%(url)s) with SHA-256 %(shasum)s to %(outfile)s",
                url=url,
                outfile=self.artifactFile.shasumFilename,
                shasum=self.artifactFile.shasum,
                destfile=self.file_to_get,
            )

            # Update the honeyfs to point to downloaded file
            self.fs.update_realfile(self.fs.getfile(self.file_to_get),
                                    self.artifactFile.shasumFilename)
            self.fs.chown(self.file_to_get, self.protocol.user.uid,
                          self.protocol.user.gid)
Esempio n. 20
0
 def test_mkdir_upload(self):
     """Testing TFTP upload files - while recursively making directories as per the TFTP path."""
     client = tftpy.TftpClient('127.0.0.1', self.tftp_server.server.server_port)
     client.upload('/dir/dir/test.txt', self._test_file)
     gevent.sleep(3)
     _, _data_fs = conpot_core.get_vfs('tftp')
     [_file] = [i for i in _data_fs.listdir('./') if '2018-07-15 17:51:17-test-txt' in i]
     self.assertEqual(_data_fs.gettext(_file), 'This is just a test file for Conpot\'s TFTP server\n')
     _data_fs.remove(_file)
Esempio n. 21
0
def tftp_command(hostname, newfile, lastfile):

    host_backup_dir = os.path.dirname(newfile)

    if not os.path.exists(host_backup_dir):
        os.makedirs(host_backup_dir)

    client = tftpy.TftpClient(hostname, 69)
    client.download("startup-config", newfile)
Esempio n. 22
0
 def test_tftp_download(self):
     _dst_path = '/'.join(conpot.__path__ + ['tests/data/data_temp_fs/tftp/download'])
     client = tftpy.TftpClient('127.0.0.1', self.tftp_server.server.server_port)
     try:
         client.download('tftp_data.txt', _dst_path)
         gevent.sleep(3)
         self.assertTrue(filecmp.cmp(_dst_path, self._test_file))
     finally:
         _, _data_fs = conpot_core.get_vfs('tftp')
         _data_fs.remove('download')
Esempio n. 23
0
 def upload(self):
     client = tftpy.TftpClient(str(self.ip_edit.text()),
                               int(self.port_edit.text()))
     try:
         client.upload(str(self.file_save_edit.text()),
                       unicode(self.file_upload_edit.text()),
                       timeout=1)
     except tftpy.TftpShared.TftpTimeout:
         QtGui.QMessageBox().warning(self, 'Ошибка',
                                     'Ошибка доступа к серверу')
Esempio n. 24
0
    def __init__(self, **kwargs):
        """
        Initialized Tapcp FPGA object
        :param host: IP Address of the targeted Board
        :return: none
        """
        Transport.__init__(self, **kwargs)

        self.t = tftpy.TftpClient(kwargs['host'], 69)
        self._logger = LOGGER
        self.timeout = kwargs.get('timeout', 3)
def main():
    ip = "192.168.195.165"
    port = 69
    tclient = tftpy.TftpClient(ip,port)
    for inc in range(0,100):
        filename = "example_router" + "-" + str(inc)
        print("[*] Attempting to download %s from %s:%s") % (filename,ip,port)
        try:
            tclient.download(filename,filename)
        except:
            print("[-] Failed to download %s from %s:%s") % (filename,ip,port)
Esempio n. 26
0
    def send_authorize_information(cls, device_ip, username, password, cli,
                                   authz_info, tftp_server, tftp_loc, uuid):
        s = slr("", "", "")
        try:
            logger.info(
                "Trying to connect to tftp server:{}".format(tftp_server))
            client = tftpy.TftpClient(tftp_server, 69)
            file_name = device_ip + ".txt"
            dest_file = dest_dir + file_name
            try:
                f = open(dest_file, "w+")
                logger.info(authz_info)
                f.write(authz_info)
                f.close()
                logger.info("Trying to upload file:{}".format(file_name))
                client.upload(file_name, dest_file)
                cli.append("lic smart reservation install file tftp://" +
                           tftp_server + "/" + file_name)
                logger.info(cli)
                SlrAuthSwitch.config_commands(device_ip, username, password,
                                              cli)
                #if dlc_status_rows is not empty means dlc is performed
                dlc_status_rows = TokensModel.get_dlc_status(uuid, device_ip)
                if dlc_status_rows:
                    dlc_status = dlc_status_rows[0][2]
                    if dlc_status == "dlc_convert_success":
                        s.update_status(SLR_REQUEST_CODE_TABLE_NAME, uuid,
                                        device_ip, "DLC Success and Completed",
                                        "step3")
                    else:
                        s.update_status(SLR_REQUEST_CODE_TABLE_NAME, uuid,
                                        device_ip,
                                        "DLC Failed and SLR Successful",
                                        "step3")
                else:
                    s.update_status(SLR_REQUEST_CODE_TABLE_NAME, uuid,
                                    device_ip, "Completed", "step3")
            except Exception as e:
                print("file upload failed:", e)
                logger.info("Failed uploading file:{}".format(file_name))
                s.update_status(SLR_REQUEST_CODE_TABLE_NAME, uuid, device_ip,
                                str(e).split(":")[0], "step3")
        except Exception as e:
            logger.info(
                "Failure connecting to tftp server:{}".format(tftp_server))
            print("Connection to tftp server failed:", e)

        rows = s.find_by_step_status(SLR_REQUEST_CODE_TABLE_NAME, uuid,
                                     "Started", "step3")
        if len(rows) == 0:
            # Updating the response status to Step 4 completed
            response_update = {'status': "S4c"}
            TokensModel.update(uuid, response_update, "upload_info_store")
        del s
Esempio n. 27
0
 async def PostFile(self, src, destname):
     await self.lock.acquire()
     try:
         t = tftpy.TftpClient(_URL)
         res = True
         t.upload(destname, src)
     except Exception as e:
         print(e)
         res = None
     self.lock.release()
     return res
Esempio n. 28
0
    def __init__(self):
        self.remote_file = 'location'
        self.local_file = 'local_file'
        self.command_file = '/tftp/command_file'

        tftp_server = '192.168.43.50'
        tftp_port = 69
        self.client = tftpy.TftpClient(tftp_server, tftp_port)

        self.last_state = 'off'
        self.current_state = 'off'
Esempio n. 29
0
 def test_tftp_download(self):
     _dst_path = "/".join(conpot.__path__ +
                          ["tests/data/data_temp_fs/tftp/download"])
     client = tftpy.TftpClient("127.0.0.1",
                               self.tftp_server.server.server_port)
     try:
         client.download("tftp_data.txt", _dst_path)
         gevent.sleep(3)
         self.assertTrue(filecmp.cmp(_dst_path, self._test_file))
     finally:
         _, _data_fs = conpot_core.get_vfs("tftp")
         _data_fs.remove("download")
Esempio n. 30
0
def read_info():

    """Function to download file from the router"""

    for i in range(0,len(ip_list)):

        connection = tftpy.TftpClient(ip_list[i], 69)
        connection.download('/startup-config', 'my_local_copy.cfg')
        data1 = open('my_local_copy.cfg')
        content1 = data1.read()

        compare_data(ip_list[i], content1)