Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

new scp file #177

Closed
wants to merge 6 commits into from
Closed
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
199 changes: 199 additions & 0 deletions library/junos_scp_file
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
#!/usr/bin/env python


# Copyright (c) 1999-2016, Juniper Networks Inc.
#
# All rights reserved.
#
# License: Apache 2.0
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# * Neither the name of the Juniper Networks nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY Juniper Networks, Inc. ''AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL Juniper Networks, Inc. BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# <*******************
#
# Copyright 2016 Juniper Networks, Inc. All rights reserved.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don;t think you can have 2 licenses for the same file : apache 2.0 and Juniper Networks Script Software License

# Licensed under the Juniper Networks Script Software License (the "License").
# You may not use this script file except in compliance with the License, which is located at
# http://www.juniper.net/support/legal/scriptlicense/
# Unless required by applicable law or otherwise agreed to in writing by the parties, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
# *******************>


DOCUMENTATION = '''
---
module: junos_scp_file
author: Boris Renet, Juniper Networks
version_added: "1.1.0"
short_description: scp a file to from a device.
description:
- scp a file to/from local directory to/from remote directory.
requirements:
- py-junos-eznc >= 1.2.3
options:
host:
description:
- Set to {{ inventory_hostname }}
required: true
user:
description:
- Login username
required: false
default: $USER
passwd:
description:
- Login password
required: false
default: assumes ssh-key active
file:
description:
- Name of the file to scp
required: true
type:
description:
- put or get depending on the direction of the scp
local_dir:
description:
- directory (without the last /) on the source of the scp
remote_dir:
description:
- directory (without the last /) on the destination of the scp
logfile:
description:
- Path on the local server where the progress status is logged
for debugging purposes
required: false
default: None
'''

EXAMPLES = '''
Copy a file from the source to the destination:
- junos_scp_file:
host={{ inventory_hostname }}
user={{ ansible_user }}
passwd={{ ansible_ssh_pass }}
local_dir="/var/tmp/junos"
remote_dir="/var/tmp"
type="put"
file={{ OS_satellite_package }}
logfile={{ log }}

Copy a file from a destination to a source:
- junos_scp_file:
host={{ inventory_hostname }}
user={{ ansible_user }}
passwd={{ ansible_ssh_pass }}
local_dir="/var/tmp"
remote_dir="/var/log"
type="get"
file="messages"
logfile={{ log }}

'''
import logging
import re
import os
from distutils.version import LooseVersion
from ansible.module_utils.basic import *

try:
from jnpr.junos import Device
from jnpr.junos.version import VERSION
if not LooseVersion(VERSION) >= LooseVersion('1.2.3'):
HAS_PYEZ = False
else:
HAS_PYEZ = True
except ImportError:
HAS_PYEZ = False

from jnpr.junos import Device
from jnpr.junos.utils.scp import SCP
def main():
module = AnsibleModule(
argument_spec=dict(
host=dict(required=True),
file=dict(required=True),
local_dir=dict(required=True),
remote_dir=dict(required=True),
user=dict(required=False, default=os.getenv('USER')),
passwd=dict(required=False, default=None),
type=dict(required=True, default=None),
logfile=dict(required=False, default=None),
),
supports_check_mode=True
)

if not HAS_PYEZ:
module.fail_json(msg='junos-eznc >= 1.2.3 is required for this module')

args = module.params

# -------------------------------------------------------------------------
# logging
# -------------------------------------------------------------------------

logfile = args['logfile']
if logfile is not None:
logging.basicConfig(filename=logfile, level=logging.INFO,
format='%(asctime)s:%(name)s:%(message)s')
logging.getLogger().name = args['host']

def do_log(msg, level='info'):
getattr(logging, level)(msg)
else:
def do_log(msg):
pass


dev = Device(args['host'], user=args['user'], password=args['passwd'])

do_log("Starting the file transfer: {0}".format(args['file']))

def update_my_progress(dev, report):
# log the progress of the installing process
do_log(report)


try:
dev.open()
if (args['type'] == "put"):
with SCP(dev,progress=update_my_progress) as scp1:
scp1.put(args['local_dir']+"/"+args['file'],remote_path=args['remote_dir'])
if (args['type'] == "get"):
with SCP(dev,progress=update_my_progress) as scp1:
scp1.get(args['remote_dir']+"/"+args['file'],local_path=args['local_dir'])
except Exception as err:
msg = 'unable to scp the file {0}: {1}'.format(args['host'], str(err))
module.fail_json(msg=msg)
return
else:
dev.close()

module.exit_json(msg="Done")

if __name__ == "__main__":
main()