def put(self, package, remote_path='/var/tmp', progress=None): """ SCP 'put' the package file from the local server to the remote device. :param str package: File path to the package file on the local file system :param str remote_path: The directory on the device where the package will be copied to. :param func progress: Callback function to indicate progress. You can use :meth:`SW.progress` for basic reporting. See that class method for details. """ def _progress(report): # report progress only if a progress callback was provided if progress is not None: progress(self._dev, report) def _scp_progress(_path, _total, _xfrd): # init static variable if not hasattr(_scp_progress, 'by10pct'): _scp_progress.by10pct = 0 # calculate current percentage xferd pct = int(float(_xfrd) / float(_total) * 100) # if 10% more has been copied, then print a message if 0 == (pct % 10) and pct != _scp_progress.by10pct: _scp_progress.by10pct = pct _progress("%s: %s / %s (%s%%)" % (_path, _xfrd, _total, str(pct))) # check for the logger barncale for 'paramiko.transport' plog = logging.getLogger('paramiko.transport') if not plog.handlers: class NullHandler(logging.Handler): def emit(self, record): pass plog.addHandler(NullHandler()) # execute the secure-copy with the Python SCP module with SCP(self._dev, progress=_scp_progress) as scp: scp.put(package, remote_path)
def put(self, package, remote_path='/var/tmp', progress=True): """ SCP 'put' the package file from the local server to the remote device. :param str package: File path to the package file on the local file system :param str remote_path: The directory on the device where the package will be copied to. :param func progress: Callback function to indicate progress. If set to True uses :meth:`scp._scp_progress` for basic reporting by default. See that class method for details. """ # execute the secure-copy with the Python SCP module with SCP(self._dev, progress=progress) as scp: scp.put(package, remote_path)
def file_copy(src=None, dest=None): ''' Copies the file from the local device to the junos device src The source path where the file is kept. dest The destination path on the where the file will be copied CLI Example: .. code-block:: bash salt 'device_name' junos.file_copy /home/m2/info.txt info_copy.txt ''' conn = __proxy__['junos.conn']() ret = {} ret['out'] = True if src is None: ret['message'] = \ 'Please provide the absolute path of the file to be copied.' ret['out'] = False return ret if not os.path.isfile(src): ret['message'] = 'Invalid source file path' ret['out'] = False return ret if dest is None: ret['message'] = \ 'Please provide the absolute path of the destination where the file is to be copied.' ret['out'] = False return ret try: with SCP(conn, progress=True) as scp: scp.put(src, dest) ret['message'] = 'Successfully copied file from {0} to {1}'.format( src, dest) except Exception as exception: ret['message'] = 'Could not copy file : "{0}"'.format(exception) ret['out'] = False return ret
def SCP_test(host): if not host.strip(): return host = host.strip(os.linesep) try: dev = Device(host=host, user=uname, password=pw, port=22, attempts=3, auto_probe=15) dev.open() except Exception as err: print('Unable to open connection to {}: {}'.format(host, err)) else: dev.timeout = 30 if dev.facts['vc_fabric'] == 'None': print("Skipping {} as EX in VC mode".format(dev.facts['hostname'])) return try: sw_ver = dev.facts['junos_info']['fpc0']['text'].strip() except KeyError: print("Unable to determine Junos version") return if dev.facts['junos_info']['fpc0']['text'].strip() != "15.1R6-S2.1": print("Skipping {} as Junos ver is {}".format( dev.facts['hostname'], dev.facts['junos_info']['fpc0']['text'])) return print('Starting RC copy process on: ', dev.facts['hostname']) with SCP(dev, progress=True) as scp: try: scp.put("12.3R12-S3.1-MOP-RC-f", remote_path="/var/home/aprinja/") except Exception as err: print('Unable to copy:', err) else: compare_checksum(host, dev)
def file_copy(src=None, dest=None): """ Copies the file from the local device to the junos device src The source path where the file is kept. dest The destination path on the where the file will be copied CLI Example: .. code-block:: bash salt 'device_name' junos.file_copy /home/m2/info.txt info_copy.txt """ conn = __proxy__["junos.conn"]() ret = {} ret["out"] = True if src is None: ret["message"] = "Please provide the absolute path of the file to be copied." ret["out"] = False return ret if not os.path.isfile(src): ret["message"] = "Invalid source file path" ret["out"] = False return ret if dest is None: ret["message"] = "Please provide the absolute path of the destination where the file is to be copied." ret["out"] = False return ret try: with SCP(conn, progress=True) as scp: scp.put(src, dest) ret["message"] = "Successfully copied file from {0} to {1}".format( src, dest) except Exception as exception: # pylint: disable=broad-except ret["message"] = 'Could not copy file : "{0}"'.format(exception) ret["out"] = False return ret
def get_rsi(equipment): try: print( "Gathering RSI...(This takes a bit - give it time. Timeout is 10 minutes.)" ) ss = StartShell(equipment) ss.open() ss.run('cli request support information \\| save /var/tmp/' + current_date + '_py_rsi.txt', this="%", timeout=600) print("RSI Done, copying it and deleting it...\n") ss.close() with SCP(equipment, progress=True) as scp: scp.get('/var/tmp/' + current_date + "_py_rsi.txt", full_file + "_" + current_date + "_rsi.txt") fileSystem = FS(equipment) fileSystem.rm('/var/tmp/*_py_rsi.txt') except Exception as err: missedEquipment[equipment] = "Error getting RSI - " + str(err)
def install_script(lab, hostname, host_address, username, password, script, path): """Loads multiping.slax script (only for lab8 (Multicast))""" print('Loading', script) # If password is provided in loader.yml if password: try: dev = Device(host=host_address, user=username, password=password, gather_facts=False) dev.open() except ConnectError as err: print("Cannot connect to device: {0}".format(err)) return # If password set to False in loader.yml (ssh key is used) else: try: dev = Device(host=host_address, user=username, password=None, gather_facts=False) dev.open() except ConnectError as err: print("Cannot connect to device: {0}".format(err)) return local_path = LabConfigHandler(lab, hostname).lab_dir f = str(local_path + '/' + script) try: # Default progress messages with SCP(dev, progress=True) as scp1: scp1.put(f, remote_path=path) except Exception as err: print(err) return else: dev.close()
def PushOps(self, hostname): ## Shows interfaces in Smart Rack vlan ## self.hostname = hostname try: connect = Device( host=self.hostname, username=self.username, password=self.password).open() successful_message = "You have successfully loaded, iv-link.slax, mac-address-count.slax, show-bpdu-errors.slax and show-storm-errors.slax on to this device! " if connect.facts['model'] == '' with SCP(dev, progress=True) as scp: scp.put("iv-link.slax", remote_path="/var/db/scripts/op/") scp.put("mac-address-count.slax", remote_path="/var/db/scripts/op/") scp.put("show-bpdu-errors.slax", remote_path="/var/db/scripts/op/") scp.put("show-storm-errors.slax", remote_path="/var/db/scripts/op/") connect.close() return {"result": successful_message} except jnpr.junos.exception.ConnectError as err: print(' Error: ' + repr(err))
def put(self, package, remote_path='/var/tmp', progress=None): """ SCP 'put' the package file from the local server to the remote device. :param str package: File path to the package file on the local file system :param str remote_path: The directory on the device where the package will be copied to. :param func progress: Callback function to indicate progress. If set to ``True`` uses :meth:`scp._scp_progress` for basic reporting by default. See that class method for details. """ # execute FTP when connection mode if telnet if hasattr(self._dev, '_mode') and self._dev._mode=='telnet': with FTP(self._dev) as ftp: ftp.put(package, remote_path) else: # execute the secure-copy with the Python SCP module with SCP(self._dev, progress=progress) as scp: scp.put(package, remote_path)
def copy_log_to_local(dev, remote_dir, filename): """Copies a file from a remote device to a local device via SCP. Args: dev (obj): PyEZ JUNOS device object with open SSH session. remote_dir (str): Absolute path for directory holding remote log file. filename (str): Name of file to be copied. Returns: None """ logger.info('Copying log file {} to local disk...'.format(filename)) try: with SCP(dev) as scp: scp.get(os.path.join(remote_dir, filename), os.path.join(log_dir, filename)) logger.info('Duplicate IP log file copied.') logger.debug("{} -> {}".format(os.path.join(remote_dir, filename), os.path.join(log_dir, filename))) except Exception as e: logger.exception(e) raise return
def test_scp_progress(self): scp = SCP(self.dev) print(scp._scp_progress('test', 100, 50))
def test_scp_context(self, mock_connect): with SCP(self.dev) as scp: scp.get('addrbook.conf')
def file_copy(self, src, dest=None, **kwargs): if dest is None: dest = os.path.basename(src) with SCP(self.native) as scp: scp.put(src, remote_path=dest)
def run_task(self): cancel_chan = ChannelCancellation() e = threading.Event() status, data = Tools.get_config( lookup_type=c.CONFIG_LOOKUP_TYPE_GET_DEVICE_CFG, sample_device=self.sample_device) if status: if self.grp_cfg.TASKS.Provision.Cert.PortForwarding: if self.sample_device.deviceServicePlugin != c.SERVICEPLUGIN_OSSH: with SCP(self.sample_device.deviceConnection, progress=False) as scp: scp.put(c.conf.SERVICES.Ossh.LocalConfigFile, c.SSHD_PORT_FWD_PATH) self.logger.info( Tools.create_log_msg( self.task_name, self.sample_device.deviceSerial, logmsg.CERT_FILE_OK.format( self.sample_device.deviceSerial))) self.sample_device.deviceConnection.close() status, self.sample_device = Tools.create_dev_conn( self.sample_device) if status: thr = threading.Thread(target=self.do_cert_requests, args=( data, e, cancel_chan, )) thr.start() ssh_pfwd = SSHPortForward( sample_device=self.sample_device, grp_cfg=self.grp_cfg, event=e, cancel_chan=cancel_chan) ssh_pfwd.init_port_fwd() else: return False, 'Error in device connection' else: thr = threading.Thread(target=self.do_cert_requests, args=( data, e, cancel_chan, )) thr.start() ssh_pfwd = SSHPortForward(sample_device=self.sample_device, grp_cfg=self.grp_cfg, event=e, cancel_chan=cancel_chan) ssh_pfwd.init_port_fwd() else: self.do_cert_requests(datavars=data, event=None) else: self.logger.info( Tools.create_log_msg(self.task_name, self.sample_device.deviceSerial, logmsg.CERT_DEV_DATA_NOK))
def send_scp(self, localfile, remotefile): with SCP(self.dev, progress=True) as scp: scp.put(localfile, remote_path=remotefile)
def run_task(self): # this task has to run before configuration task # copy base image # make copy of base image for specific VNF # generate bootstrap conf # copy boostrap conf # make bootstrap iso # Done _vnf = Vnf() _configurator = Configuration() datavars = self.sample_device.deviceConfigData if datavars: for vnf in datavars['device']['vnfs']: self.logger.info( Tools.create_log_msg(self.task_name, self.sample_device.deviceSerial, logmsg.VNFSTAGE_SETUP_DIR)) sftp = SFTPClient.from_transport( self.sample_device.deviceConnection._conn._session. _transport) _vnf.mkdir_p(sftp, vnf['bootstrap_remote_dir'] + vnf['name']) # Copy base image and boostrap conf try: with SCP(self.sample_device.deviceConnection, progress=False) as scp: self.update_task_state( new_task_state=c.TASK_STATE_PROGRESS, task_state_message=logmsg.VNFSTAGE_CP_BASE_IMG. format(vnf['base_img'], self.sample_device.deviceIP, vnf['base_img_path'])) self.logger.info( Tools.create_log_msg( self.task_name, self.sample_device.deviceSerial, logmsg.VNFSTAGE_CP_BASE_IMG.format( vnf['base_img'], self.sample_device.deviceIP, vnf['base_img_path']))) scp.put('images/' + vnf['base_img'], vnf['base_img_path']) self.logger.info( Tools.create_log_msg( self.task_name, self.sample_device.deviceSerial, logmsg.VNFSTAGE_MAKE_CP_BASE_IMG_OK.format( vnf['name']))) self.logger.info( Tools.create_log_msg( self.task_name, self.sample_device.deviceSerial, logmsg.VNFSTAGE_GEN_BOOTSTRAP.format( vnf['name']))) except OSError as ose: self.update_task_state( new_task_state=c.TASK_STATE_FAILED, task_state_message=logmsg.VNFSTAGE_CP_ERR.format( vnf['name'], ose.strerror, ose.filename)) self.logger.info( Tools.create_log_msg( self.task_name, self.sample_device.deviceSerial, logmsg.VNFSTAGE_CP_ERR.format( vnf['name'], ose.strerror, ose.filename))) return vnf_conf_file = _configurator.prepare_vnf_boostrap_config( serialnumber=vnf['deviceID'], grp_cfg=self.grp_cfg, vnf_type=vnf['vnf_type']) if vnf_conf_file is not None: full_path = self.grp_cfg.TASKS.Provision.Configuration.ConfigFileHistory + vnf_conf_file with SCP(self.sample_device.deviceConnection, progress=False) as scp: self.update_task_state( new_task_state=c.TASK_STATE_PROGRESS, task_state_message=logmsg.VNFSTAGE_COPY_BOOTSTRAP. format( full_path, self.sample_device.deviceIP, vnf['bootstrap_remote_dir'] + vnf['name'] + '/')) self.logger.info( Tools.create_log_msg( self.task_name, self.sample_device.deviceSerial, logmsg.VNFSTAGE_COPY_BOOTSTRAP.format( full_path, self.sample_device.deviceIP, vnf['bootstrap_remote_dir'] + vnf['name'] + '/'))) try: scp.put( full_path, vnf['bootstrap_remote_dir'] + vnf['name'] + '/' + 'juniper.conf') self.logger.info( Tools.create_log_msg( self.task_name, self.sample_device.deviceSerial, logmsg.VNFSTAGE_COPY_BOOTSTRAP_OK.format( vnf['name']))) except OSError as ose: self.update_task_state( new_task_state=c.TASK_STATE_FAILED, task_state_message=logmsg.VNFSTAGE_CP_ERR. format(vnf['name'], ose.strerror, ose.filename)) self.logger.info( Tools.create_log_msg( self.task_name, self.sample_device.deviceSerial, logmsg.VNFSTAGE_CP_ERR.format( vnf['name'], ose.strerror, ose.filename))) return # Make copy of base image self.update_task_state( new_task_state=c.TASK_STATE_PROGRESS, task_state_message=logmsg.VNFSTAGE_MAKE_CP_BASE_IMG. format(vnf['name'])) self.logger.info( Tools.create_log_msg( self.task_name, self.sample_device.deviceSerial, logmsg.VNFSTAGE_MAKE_CP_BASE_IMG.format( vnf['name']))) req1 = '{0} {1}{2} {3}{4}{5}'.format( 'file copy', vnf['base_img_path'], vnf['base_img'], vnf['base_img_path'], vnf['name'], '.qcow2') self.sample_device.deviceConnection.cli(command=req1, format='text', warning=False) self.logger.info( Tools.create_log_msg( self.task_name, self.sample_device.deviceSerial, logmsg.VNFSTAGE_MAKE_CP_BASE_IMG_OK.format( vnf['name']))) # Genisoimage self.update_task_state( new_task_state=c.TASK_STATE_PROGRESS, task_state_message=logmsg.VNFSTAGE_GEN_BOOTSTRAP. format(vnf['name'])) self.logger.info( Tools.create_log_msg( self.task_name, self.sample_device.deviceSerial, logmsg.VNFSTAGE_GEN_BOOTSTRAP.format(vnf['name']))) req2 = '{0} {1}{2}{3}{4} {5}{6}{7}{8}{9}'.format( 'request genisoimage', vnf['bootstrap_remote_dir'], vnf['name'], '/', 'juniper.conf', vnf['bootstrap_remote_dir'], vnf['name'], '/', vnf['name'], '.iso') self.sample_device.deviceConnection.cli(command=req2, format='text', warning=False) self.update_task_state( new_task_state=c.TASK_STATE_PROGRESS, task_state_message=logmsg.VNFSTAGE_BOOSTRAP_OK.format( vnf['name'])) self.logger.info( Tools.create_log_msg( self.task_name, self.sample_device.deviceSerial, logmsg.VNFSTAGE_BOOSTRAP_OK.format(vnf['name']))) else: self.update_task_state( new_task_state=c.TASK_STATE_FAILED, task_state_message=c.TASK_STATE_MSG_FAILED) return self.update_task_state( new_task_state=c.TASK_STATE_DONE, task_state_message=c.TASK_STATE_MSG_DONE) else: self.update_task_state( new_task_state=c.TASK_STATE_FAILED, task_state_message=logmsg.VNFSTAGE_DEV_CONF_READ_ERR) self.logger.info( Tools.create_log_msg(self.task_name, self.sample_device.deviceSerial, logmsg.VNFSTAGE_DEV_CONF_READ_ERR)) return
def run_task(self): Tools.emit_log(task_name=self.task_name, sample_device=self.sample_device, message=logmsg.CP_INIT.format( self.grp_cfg.TASKS.Provision.Filecp.Files)) if self.sample_device.deviceConnection.connected: try: if c.SERVICEPLUGIN_OSSH == self.sample_device.deviceServicePlugin: with SCPClient(self.sample_device.deviceConnection._conn. _session.transport) as scp: for _file in self.grp_cfg.TASKS.Provision.Filecp.Files: self.update_task_state( new_task_state=c.TASK_STATE_PROGRESS, task_state_message=logmsg.CP_COPY.format( _file)) Tools.emit_log( task_name=self.task_name, sample_device=self.sample_device, message=logmsg.CP_COPY.format(_file)) scp.put( self.grp_cfg.TASKS.Provision.Filecp. FileLocalDir + _file, self.grp_cfg.TASKS. Provision.Filecp.FileRemoteDir) Tools.emit_log( task_name=self.task_name, task_state={ 'taskState': self.task_state, 'taskStateMsg': c.TASK_STATE_MSG_DONE }, sample_device=self.sample_device, grp_cfg=self.grp_cfg, shared=self.shared, message=logmsg.CP_SUCCESS.format(_file), scope=c.LOGGER_SCOPE_ALL, level=c.LOGGER_LEVEL_INFO) self.update_task_state( new_task_state=c.TASK_STATE_DONE, task_state_message=c.TASK_STATE_MSG_DONE) else: with SCP(self.sample_device.deviceConnection, progress=False) as scp: for _file in self.grp_cfg.TASKS.Provision.Filecp.Files: self.update_task_state( new_task_state=c.TASK_STATE_PROGRESS, task_state_message=logmsg.CP_COPY.format( _file)) Tools.emit_log( task_name=self.task_name, sample_device=self.sample_device, message=logmsg.CP_COPY.format(_file)) scp.put( self.grp_cfg.TASKS.Provision.Filecp. FileLocalDir + _file, self.grp_cfg.TASKS. Provision.Filecp.FileRemoteDir) Tools.emit_log( task_name=self.task_name, task_state={ 'taskState': self.task_state, 'taskStateMsg': c.TASK_STATE_MSG_DONE }, sample_device=self.sample_device, grp_cfg=self.grp_cfg, shared=self.shared, message=logmsg.CP_SUCCESS.format(_file), scope=c.LOGGER_SCOPE_ALL, level=c.LOGGER_LEVEL_INFO) self.update_task_state( new_task_state=c.TASK_STATE_DONE, task_state_message=c.TASK_STATE_MSG_DONE) except (paramiko.BadHostKeyException, paramiko.AuthenticationException) as e: Tools.emit_log(task_name=self.task_name, sample_device=self.sample_device, message=logmsg.CP_FAILED.format(e.message)) self.update_task_state( new_task_state=c.TASK_STATE_FAILED, task_state_message=logmsg.CP_FAILED.format(e.message)) else: Tools.emit_log(task_name=self.task_name, sample_device=self.sample_device, message=logmsg.CP_FAILED_NO_CONN) self.update_task_state(new_task_state=c.TASK_STATE_FAILED, task_state_message=logmsg.CP_FAILED_NO_CONN)
def fileloader(self, package, remotepath): with SCP(self.jnprdev) as scp: try: scp.put(package, remotepath) except Exception as err: raise jException(err, self.hostname)
ret["out"] = False return ret if not os.path.isfile(src): ret["message"] = "Invalid source file path" ret["out"] = False return ret if dest is None: ret[ "message" ] = "Please provide the absolute path of the destination where the file is to be copied." ret["out"] = False return ret try: with SCP(conn, progress=True) as scp: scp.put(src, dest) ret['message'] = 'Successfully copied file from {0} to {1}'.format( src, dest) except Exception as exception: ret['message'] = 'Could not copy file : "{0}"'.format(exception) ret['out'] = False return ret def lock(): """ Attempts an exclusive lock on the candidate configuration. This is a non-blocking call.
def get_file(self): d = dev(host=self.ip, user='******', password='******').open() with SCP(d) as scp: print("Fetching file - traffic-capture.pcap") scp.get('traffic-capture.pcap') print('Fetch Done!')
def test_scp_progress(self): scp = SCP(self.dev) print scp._scp_progress('test', 100, 50)
def junos_scp(self, mode, local, remote): with SCP(self.device, progress=True) as scp: if mode == 'put': scp.put(local, remote_path=remote) elif mode == 'get': scp.get(remote, local_path=local)
def recv_scp(self, remotefile): with SCP(self.dev, progress=True) as scp: scp.get(remote_path=remotefile)
from jnpr.junos.utils.start_shell import StartShell from lxml import etree from jnpr.junos.utils.scp import SCP # connect to the device with IP-address, login user and passwort dev = Device(host="10.49.236.63", user="******", password="******", port=22, gather_facts=False) dev.open() # Increase timeout to 600 sec. dev.timeout = 600 print("Connection successfully...") # Open a new shell connection via StartShell (Paramiko) ss = StartShell(dev) ss.open() ss.run('cli -c "request support information | save /var/tmp/pyez_rsi2.txt"') # Transfer file via SCP with SCP(dev, progress=True) as scp: scp.get("/var/tmp/pyez_rsi2.txt", "rsi2.txt") ss.run('rm /var/tmp/pyez_rsi*') ss.close() # Close connection to the device dev.close() print("Connection closed...")
from jnpr.junos import Device from jnpr.junos.utils.scp import SCP import datetime import os now = datetime.datetime.now() new_dir = '/home/watashi/config/auto_get/'+now.strftime('%y%m%d_%H%M%S') os.mkdir(new_dir) USER = "******" PASSWD = "pppp" DEVICE = [ "NODE1", "NODE2", "NODE3", "NODE4" , ] for d in DEVICE: dev = Device(host=d, user=USER, password=PASSWD) with SCP(dev) as scp: scp.get("/config/juniper.conf", local_path=new_dir+'/'+d+"_juniper.conf")
g_msg.append(e) print(e) exit() finally: vpn_log.f_log(g_msg) # print "Connected" g_msg.append("Connected") # Retrieving the KMD log file and creating the local directory (if needed) # print "Retrieving the VPN Log File" g_msg.append("Retrieving the VPN Log File") try: # Default progress messages with SCP(dev, progress=True) as kmd_file: kmd_file.get("/var/log/kmd-logs", local_path="./") except ConnectError as e: # print "Could not retrieve the VPN log file, exiting" g_msg.append("Could not retrieve the VPN log file, exiting") g_msg.append(e) print(e) exit() finally: vpn_log.f_log(g_msg) # print "VPN Log file successfully retrieved" g_msg.append("VPN Log file successfully retrieved") # Closing Connection to the SRX device # print "Closing Connection to:", g_input_IP