├── .gitignore
├── .vscode
└── launch.json
├── Ansible
├── Intro
│ ├── condition.yml
│ ├── condition2.yml
│ ├── facts.yml
│ ├── loops.yml
│ ├── playbook.yml
│ ├── setup.sh
│ ├── stats.yml
│ └── variables.yml
├── Junos
│ ├── facts.yml
│ ├── host_vars
│ │ ├── 10.10.10.150.yml
│ │ └── 10.10.10.151.yml
│ ├── vlan.yml
│ └── vlans.yml
├── eveng
│ ├── lab1
│ │ ├── baseconfig.yml
│ │ ├── group_vars
│ │ │ └── lab1.yml
│ │ └── host_vars
│ │ │ ├── 10.10.21.200.yml
│ │ │ ├── 10.10.21.202.yml
│ │ │ ├── 10.10.21.203.yml
│ │ │ ├── 10.10.21.204.yml
│ │ │ ├── 10.10.21.205.yml
│ │ │ ├── 10.10.21.206.yml
│ │ │ ├── 10.10.21.207.yml
│ │ │ └── 10.10.21.208.yml
│ ├── lab2
│ │ ├── group_vars
│ │ │ └── lab2.yml
│ │ ├── host_vars
│ │ │ ├── 10.10.21.211.yml
│ │ │ ├── 10.10.21.212.yml
│ │ │ ├── 10.10.21.213.yml
│ │ │ ├── 10.10.21.214.yml
│ │ │ ├── 10.10.21.215.yml
│ │ │ ├── 10.10.21.216.yml
│ │ │ ├── 10.10.21.217.yml
│ │ │ ├── 10.10.21.218.yml
│ │ │ ├── 10.10.21.219.yml
│ │ │ ├── 10.10.21.220.yml
│ │ │ └── 10.10.21.221.yml
│ │ └── ipv4config.yml
│ └── lab3
│ │ ├── group_vars
│ │ └── lab3.yml
│ │ ├── host_vars
│ │ ├── 10.10.21.231.yml
│ │ ├── 10.10.21.232.yml
│ │ ├── 10.10.21.233.yml
│ │ ├── 10.10.21.234.yml
│ │ ├── 10.10.21.235.yml
│ │ ├── 10.10.21.236.yml
│ │ ├── 10.10.21.237.yml
│ │ ├── 10.10.21.238.yml
│ │ ├── 10.10.21.239.yml
│ │ └── 10.10.21.240.yml
│ │ └── lab3config.yml
├── iosxe
│ ├── facts.yml
│ └── show.yml
├── networking
│ ├── .ansible_env
│ ├── delLoop.yml
│ ├── group_vars
│ │ └── switches.yml
│ ├── host_vars
│ │ ├── 172.16.1.4.yml
│ │ └── 172.16.1.68.yml
│ ├── loopback.yml
│ └── network.yml
└── restconf
│ ├── files
│ └── ietf_inteface.j2
│ ├── host_vars
│ ├── 172.16.1.25.yml
│ └── ios-xe-mgmt-latest.cisco.com.yml
│ ├── jinja.yml
│ ├── output.json
│ ├── restconf_config.yml
│ └── restconf_get.yml
├── Postman
├── DNA
│ ├── DNA.postman_collection.json
│ ├── DNA.postman_environment.json
│ ├── client-health response.json
│ └── network-topology.json
├── IOS-XE
│ ├── IOS-XE.postman_collection.json
│ └── IOS-XE.postman_environment.json
├── Meraki
│ ├── Meraki.postman_collection.json
│ └── Meraki.postman_environment.json
└── Restconf-YANG
│ └── Restconf.postman_collection.json
├── Powershell
├── Networking
│ ├── RESTCONF.ps1
│ ├── aci.ps1
│ ├── dna.ps1
│ ├── meraki.ps1
│ ├── sdwan.ps1
│ ├── ubnt.ps1
│ └── ucs.ps1
├── Powershell7
│ ├── ActiveDirectory
│ │ ├── ADGroups.ps1
│ │ ├── PSDrive.ps1
│ │ ├── Users.ps1
│ │ └── userprops.ps1
│ ├── Azure
│ │ ├── connect.ps1
│ │ ├── networks.ps1
│ │ ├── rgs.ps1
│ │ ├── shutdown.ps1
│ │ └── vms.ps1
│ ├── CommonTasks
│ │ ├── email.ps1
│ │ ├── jobs.ps1
│ │ └── remoting.ps1
│ ├── Data
│ │ ├── csv.ps1
│ │ ├── excel.ps1
│ │ ├── json.ps1
│ │ ├── sql.ps1
│ │ └── sw.json
│ ├── Linux
│ │ ├── help.ps1
│ │ ├── os.ps1
│ │ └── services.ps1
│ ├── Modules
│ │ ├── install.ps1
│ │ ├── module.ps1
│ │ └── uninstall.ps1
│ ├── OS
│ │ ├── cim.ps1
│ │ ├── env.ps1
│ │ ├── files.ps1
│ │ └── nav.ps1
│ ├── RealWorld
│ │ ├── ftpauto.ps1
│ │ └── jsonsql.ps1
│ └── Web
│ │ ├── api.ps1
│ │ ├── ftp.ps1
│ │ ├── pokeapi.ps1
│ │ ├── postapi.ps1
│ │ ├── webdownload.ps1
│ │ └── webparse.ps1
└── az500
│ └── storage
│ └── byok.ps1
├── Python
├── AppDev
│ ├── Dockerfile
│ ├── app
│ │ ├── db.txt
│ │ ├── filename.log
│ │ ├── myApi.py
│ │ ├── myApi_ub.py
│ │ └── routerclass.py
│ ├── docker-compose.yml
│ ├── init.sh
│ ├── requirements.txt
│ └── tests
│ │ └── test_flask.py
├── Azure
│ ├── Functions
│ │ ├── .funcignore
│ │ ├── .gitignore
│ │ ├── Meraki
│ │ │ ├── __init__.py
│ │ │ ├── function.json
│ │ │ └── sample.dat
│ │ ├── host.json
│ │ ├── proxies.json
│ │ └── requirements.txt
│ └── MerakiLocationScan
│ │ ├── .funcignore
│ │ ├── .gitignore
│ │ ├── .vscode
│ │ ├── extensions.json
│ │ ├── launch.json
│ │ ├── settings.json
│ │ └── tasks.json
│ │ ├── MerakiLoc
│ │ ├── __init__.py
│ │ ├── function.json
│ │ └── sample.dat
│ │ ├── host.json
│ │ ├── proxies.json
│ │ └── requirements.txt
├── Data
│ ├── azkvdemo.py
│ ├── demo.html
│ ├── security.py
│ ├── sql.py
│ ├── starwars.py
│ ├── starwars.xlsx
│ └── swexcel.py
├── Docker
│ ├── Dockerfile
│ ├── build.sh
│ ├── install.sh
│ ├── myAPI
│ │ └── myAPI.py
│ ├── requirements.txt
│ ├── sqlcont.sh
│ └── swdocker.sh
└── Networking
│ ├── ACI
│ ├── ACI Requests.py
│ └── ACItoolkit.py
│ ├── Collaboration
│ ├── cleanup.py
│ ├── uds Get Users.py
│ ├── webex sdk.py
│ └── webex.py
│ ├── DNA
│ ├── Client-Health.py
│ ├── DNACauth.py
│ ├── DNACclienthealth.py
│ ├── DNACcommandrunner.py
│ ├── DNACcreatesite.py
│ ├── DNACdevices.py
│ ├── DNACdiscovery.py
│ ├── DNACgetsites.py
│ ├── DNACsdadev.py
│ ├── ENAUTOauthentication.py
│ ├── ENAUTOclienthealth.py
│ ├── ENAUTOcommandrunner.py
│ ├── ENAUTOdevdiscovery.py
│ ├── ENAUTOdna.py
│ ├── ENAUTOgetinventory.py
│ ├── ENAUTOgetsites.py
│ ├── ENAUTOwebhooks.py
│ ├── auth.py
│ ├── client-detail wifi.py
│ ├── createsite.py
│ ├── dnademo.py
│ ├── dnasdk.py
│ ├── getsite.py
│ └── getsitetop.py
│ ├── IOS-XE
│ ├── EANUTOrestconfcapabilities.py
│ ├── ENAUTOcapabilities.py
│ ├── ENAUTOedit.py
│ ├── ENAUTOget.py
│ ├── ENAUTOnetmiko.py
│ ├── ENAUTOrestconfGET.py
│ ├── ENAUTOrestconfPOST.py
│ ├── ENAUTOtelemetry.py
│ ├── __pycache__
│ │ └── interfaces.cpython-37.pyc
│ ├── csr8000v.yml
│ ├── ios_config.xml
│ ├── netconf ENCOR.py
│ ├── netconf-1.py
│ ├── netconf-2.py
│ ├── netconf-3.py
│ ├── netconf-4.py
│ ├── netconf-5.py
│ ├── netconf-editconfig.py
│ ├── netconf-eigrp-yang.py
│ ├── netconf-filter.xml
│ ├── netconfdemo.py
│ ├── powerbi.py
│ ├── pyangdemo.py
│ ├── pyangint.py
│ ├── restconf ENCOR.py
│ ├── restconf-get.py
│ ├── router_info.py
│ ├── scrapli-yang
│ │ ├── nc-rpc.py
│ │ ├── nc-subtree.py
│ │ └── nc-xpath.py
│ ├── scrapli
│ │ ├── mydevice.py
│ │ ├── netconf-subtree.py
│ │ ├── netconf-xpath.py
│ │ └── scrapli-xpathrpc.py
│ ├── scrpli-eigrp.py
│ └── yangdemo.py
│ ├── IOS
│ ├── cli.py
│ ├── show int trunks.py
│ ├── show int.py
│ ├── show ints.py
│ ├── show ip int br.py
│ ├── show ip int brief.py
│ ├── show spann.py
│ ├── showver.py
│ └── spann.py
│ ├── Junos
│ ├── Untitled-1.py
│ ├── facts.py
│ ├── getconfig.py
│ ├── junos.py
│ ├── netconf.sh
│ ├── pyez-config.py
│ ├── pyez-exception.py
│ ├── pyez-facts.py
│ ├── pyez-geconfig.py
│ ├── pyez-rpc.py
│ ├── restapi.py
│ ├── rpc_get_sample.xml
│ └── rpc_set_example.xml
│ ├── Meraki
│ ├── DEVCORenableSSID.py
│ ├── DEVCORgetnets.py
│ ├── DEVCORgetssids.py
│ ├── ENAUTOgetorgs.py
│ ├── ENAUTOmerakiCRUD.py
│ ├── MerakiSDK.py
│ ├── client usage.py
│ ├── get client events.py
│ ├── get licenses.py
│ ├── get meraki admins.py
│ ├── get net traffic.py
│ ├── get switch settings.py
│ ├── get traffic shaping.py
│ ├── getclients.py
│ ├── getclienttraffic.py
│ ├── getdevices.py
│ ├── getnetworks.py
│ ├── getvlans.py
│ └── merakidemo.py
│ ├── NAPALM
│ └── napalmdemo.py
│ ├── NSO
│ ├── bash commands.sh
│ └── nso.py
│ ├── NX-API
│ ├── NXAPI-RealWorld.py
│ └── nxapi.py
│ ├── Nornir
│ ├── bgp_deploy.py
│ ├── bgp_options.j2
│ ├── bgp_template.j2
│ ├── clean_ospf.py
│ ├── config-yml.py
│ ├── config.yml
│ ├── defaults
│ │ └── default.yml
│ ├── del_ospf.py
│ ├── groups
│ │ └── groups.yml
│ ├── helloworld.py
│ ├── hosts
│ │ └── hosts.yml
│ ├── interfaces.j2
│ ├── isis_config.j2
│ ├── isis_interfaces.j2
│ ├── juniperfacts.py
│ ├── junos_isis_template.py
│ ├── junos_ospf_template.py
│ ├── junosintterse.py
│ ├── junospf.py
│ ├── lacp_chassis.j2
│ ├── lacp_ints.j2
│ ├── lacp_template.py
│ ├── nornir.log
│ ├── ospf.j2
│ ├── rpctest.py
│ ├── scraplisis.py
│ ├── shisisnei.py
│ └── thirty_one_maker.py
│ ├── PyATSGenie
│ └── testbed.yml
│ ├── PyNTC
│ └── junos.py
│ ├── SDWAN
│ ├── ENAUTOadminapi.py
│ ├── ENAUTOauthentication.py
│ ├── ENAUTOcertmgmt.py
│ ├── ENAUTOcreatetemplates.py
│ ├── ENAUTOdeviceinventory.py
│ ├── ENAUTOgetdata.py
│ ├── ENAUTOgettemplates.py
│ ├── ENSDWI
│ │ ├── datetimehandler.py
│ │ ├── ensdwiauth.py
│ │ ├── ensdwibfdstats.py
│ │ ├── ensdwicontrolconn.py
│ │ ├── ensdwidevices.py
│ │ ├── ensdwievents.py
│ │ ├── ensdwitunnelstats.py
│ │ └── main.py
│ └── Get Devices.py
│ ├── Security
│ ├── ASA.py
│ ├── fmc access pol assign.py
│ ├── fmc create policy.py
│ └── fmc get apps.py
│ ├── UCS
│ └── ucs.py
│ └── Ubiquiti
│ └── ubnt.py
├── README.md
├── SQL
├── DP300
│ ├── Backups
│ │ ├── SWDB_schema.sql
│ │ ├── backup_filegroups.sql
│ │ ├── backups.sql
│ │ ├── restore.sql
│ │ ├── restore_filegroups.sql
│ │ └── restore_pages.sql
│ ├── FCI
│ │ └── create_cluster.ps1
│ ├── SampleData
│ │ ├── createClinicsDB.sql
│ │ └── createNLDB.sql
│ ├── alwaysenc
│ │ ├── Program.cs
│ │ └── azkv.ps1
│ ├── audit
│ │ └── changetrack.sql
│ ├── authentication
│ │ └── auth.sql
│ ├── authorization
│ │ ├── db.sql
│ │ ├── server.sql
│ │ └── tier.sql
│ ├── encAtRest
│ │ ├── Cell level enc.sql
│ │ ├── TDE.sql
│ │ ├── ddmask.sql
│ │ └── diskenc.ps1
│ ├── identify query issue
│ │ └── querystore.sql
│ ├── index
│ │ ├── fragment.sql
│ │ ├── fragment_cstore.sql
│ │ ├── missing.sql
│ │ └── utilization.sql
│ └── sec
│ │ └── az_tde.ps1
└── DP500
│ ├── Adv Data Sources
│ ├── demo.pbix
│ ├── deploy_ml_model.ipynb
│ ├── ml_rpt.pbix
│ ├── swapi_people.json
│ └── yellow_tripdata_2022-04.parquet
│ ├── PREDICT
│ ├── build.py
│ ├── build_model.ipynb
│ ├── cali1.model.onnx
│ ├── features.csv
│ └── target.csv
│ ├── Pwsh Monitor
│ └── pwsh.ps1
│ ├── Query DW
│ ├── bigger sum.sql
│ ├── rank.sql
│ ├── snowflake.sql
│ └── sum.sql
│ ├── Query Synapse
│ ├── product1.json
│ └── product2.json
│ ├── sourcecontrol
│ ├── DevOpsProd-basedata.bim
│ ├── DevOpsProd-basedata.khutc.tmuo
│ ├── OLS.pbix
│ ├── basedata.pbix
│ ├── basedatamodel.bim
│ ├── basedatamodel.khutc.tmuo
│ ├── calcgrps.pbix
│ ├── demo.sql
│ ├── drls.pbix
│ ├── functions.pbix
│ ├── rls.pbix
│ ├── sampledatafoodsales.xlsx
│ └── sqlrls.pbix
│ └── spark query
│ ├── SalesOrderDetail.csv
│ ├── basic_query.ipynb
│ ├── create_catalog.ipynb
│ ├── define_schema.ipynb
│ └── sql_query.ipynb
├── env.py
└── sqlscript
├── ExternalSrcs.json
├── Filepath.json
├── Qry_JSON_columns.json
├── Query_JSON.json
├── Serverless-Curr-Defined.json
└── Serverless-Currency-Infer.json
/.gitignore:
--------------------------------------------------------------------------------
1 | Python/Networking/IOS/.env
2 | Docker2/requirements.txt
3 | Docker2/Dockerfile
4 | .env
5 | Python/os.py
6 |
7 | .python_packages
8 | __pycache__
9 | .venv
10 | test.py
11 |
12 | .python_packages
13 | __pycache__
14 | .venv
15 | gpw.py
16 | Python/Azure/init.py
17 | Powershell/MerakiSDK/sdktest.ps1
18 | .vscode/settings.json
19 | .vscode/settings.json
20 | .vscode/settings.json
21 | .vscode/settings.json
22 | Python/Networking/Nornir/yamlizer.py
23 | nornir.log
24 | nornir.log
25 |
--------------------------------------------------------------------------------
/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | // Use IntelliSense to learn about possible attributes.
3 | // Hover to view descriptions of existing attributes.
4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5 | "version": "0.2.0",
6 | "configurations": [
7 | {
8 | "name": "Python: Current File",
9 | "type": "python",
10 | "request": "launch",
11 | "program": "${file}",
12 | "console": "integratedTerminal"
13 | },
14 | {
15 | "name": "Attach to Python Functions",
16 | "type": "python",
17 | "request": "attach",
18 | "port": 9091,
19 | "preLaunchTask": "func: host start"
20 | },
21 | {
22 | "name": "Python: Flask",
23 | "type": "python",
24 | "request": "launch",
25 | "module": "flask",
26 | "env": {
27 | "FLASK_APP": "C:\\Code\\CodeSamples\\Python\\AppDev\\myApi.py",
28 | "FLASK_ENV": "development",
29 | "FLASK_DEBUG": "0"
30 | },
31 | "args": [
32 | "run",
33 | "--no-debugger"
34 | ],
35 | "jinja": true
36 | }
37 | ]
38 | }
--------------------------------------------------------------------------------
/Ansible/Intro/condition.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - hosts: linuxhosts
3 | become: true
4 | tasks:
5 | - name: install nginx on ubuntu
6 | apt: name=nginx state=latest
7 | # This will generate an error on CentOS
8 | ignore_errors: yes
9 | # When it fails, want to store the failure in a variable
10 | # for next task to run in case of failure
11 | register: results
12 |
13 | - name: install nginx on centos
14 | yum: name=nginx state=latest
15 | when: results|failed
16 |
--------------------------------------------------------------------------------
/Ansible/Intro/condition2.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - hosts: linuxhosts
3 | become: true
4 | tasks:
5 | - name: uninstall nginx on ubuntu
6 | apt: name=nginx state=absent
7 | when: ansible_os_family == "Debian"
8 |
9 | - name: uninstall nginx on centos
10 | yum: name=nginx state=absent
11 | when: ansible_os_family == "RedHat"
12 |
--------------------------------------------------------------------------------
/Ansible/Intro/facts.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - hosts: ubuntu
3 | # facts demo
4 | # ansible ubuntu -m setup
5 | # ansible ubuntu -m setup -a "filter=*ansible_os_family"
6 | # ansible ubuntu -m setup -a "filter=*ansible_user_id"
7 | tasks:
8 | - name: print OS family to file
9 | shell: echo "The family is {{ansible_os_family}}" > /home/{{ansible_user_id}}/Desktop/family.txt
10 | - name: Print Default Machine NIC Name to console
11 | debug: msg="{{ansible_default_ipv4.interface}}"
12 | - name: Register ls results variable
13 | command: "ls"
14 | register: dirs
15 | - name: Print dirs variable from last step to console
16 | debug:
17 | msg: "{{dirs}}"
18 |
--------------------------------------------------------------------------------
/Ansible/Intro/loops.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Demo Ansible loops
3 | hosts: ubuntu
4 | become: yes
5 | tasks:
6 | - name: Create a file
7 | shell: echo 'Begin file' > /home/knox/Desktop/loops.txt
8 | - name: install packages
9 | shell: echo "{{item}}" >> /home/knox/Desktop/loops.txt
10 | with_items:
11 | - vim
12 | - nano
13 | - python
14 |
--------------------------------------------------------------------------------
/Ansible/Intro/playbook.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - hosts: linuxhosts
3 | tasks:
4 | - name: get system status
5 | shell: uname -a > /home/knox/Desktop/output.txt
6 | - name: print current user
7 | shell: whoami >> /home/knox/Desktop/output.txt
8 |
--------------------------------------------------------------------------------
/Ansible/Intro/stats.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Get stats and write to desktop
3 | hosts: linuxhosts
4 | tasks:
5 | - name: get system status and info
6 | shell: uname -a > /home/knox/Desktop/output.txt
7 | - name: print my username
8 | shell: whoami >> /home/knox/Desktop/output.txt
--------------------------------------------------------------------------------
/Ansible/Intro/variables.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Playbook with variables demo
3 | hosts: linuxhosts
4 | vars:
5 | - var1: zig
6 | - var2: zag
7 | tasks:
8 | - name: print data
9 | shell: echo "{{var1}} when you should {{var2}}" > /home/knox/Desktop/vars.txt
10 |
--------------------------------------------------------------------------------
/Ansible/Junos/facts.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Gather device facts
3 | hosts: 10.10.10.150
4 | tasks:
5 | - name: gather facts
6 | junos_facts:
7 | register: response
8 | - name: debug
9 | debug:
10 | var: response
11 | - name: debug more
12 | debug:
13 | var: ansible_net_memfree_mb
14 | - name: debug even more
15 | debug:
16 | var: ansible_net_interfaces.me0
--------------------------------------------------------------------------------
/Ansible/Junos/host_vars/10.10.10.150.yml:
--------------------------------------------------------------------------------
1 | ---
2 | ansible_connection: netconf
3 | ansible_network_os: junos
4 | ansible_user: root
5 | ansible_password:
6 |
7 | vlan:
8 | - name: vlan102
9 | vlanid: 102
10 | - name: vlan103
11 | vlanid: 103
--------------------------------------------------------------------------------
/Ansible/Junos/host_vars/10.10.10.151.yml:
--------------------------------------------------------------------------------
1 | ---
2 | ansible_connection: netconf
3 | ansible_network_os: junos
4 | ansible_user: root
5 | ansible_password:
6 |
7 | vlan:
8 | - name: vlan102
9 | vlanid: 102
10 | - name: vlan103
11 | vlanid: 103
--------------------------------------------------------------------------------
/Ansible/Junos/vlan.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Create VLAN 101
3 | hosts: junos-switches
4 | connection: local
5 | tasks:
6 | - name: Create vlan101
7 | junos_vlans:
8 | config:
9 | - name: vlan101
10 | vlan_id: 101
11 | state: merged
--------------------------------------------------------------------------------
/Ansible/Junos/vlans.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Create vlan
3 | hosts: junos-switches
4 | tasks:
5 | - name: Create vlans on devices
6 | with_items: "{{vlan}}"
7 | junos_vlans:
8 | config:
9 | - name: "{{item.name}}"
10 | vlan_id: "{{item.vlanid}}"
11 | state: merged
--------------------------------------------------------------------------------
/Ansible/eveng/lab1/baseconfig.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Issue show commands
3 | hosts: lab1
4 | connection: local
5 | gather_facts: no
6 | tasks:
7 | - name: Create Loopback
8 | with_items: "{{local_loopback}}"
9 | ios_interfaces:
10 | config:
11 | - name: "{{item.name}}"
12 | enabled: True
13 | state: merged
14 |
15 | - name: Set Loopback IP
16 | with_items: "{{local_loopback}}"
17 | ios_l3_interface:
18 | name: "{{item.name}}"
19 | ipv4: "{{item.ip_address}}"
20 |
21 | - name: Set Interface IPs
22 | with_items: "{{interfaces}}"
23 | ios_l3_interface:
24 | name: "{{item.name}}"
25 | ipv4: "{{item.ip_address}}"
26 |
27 | - name: No shut
28 | with_items: "{{interfaces}}"
29 | ios_interfaces:
30 | config:
31 | - name: "{{item.name}}"
32 | enabled: True
33 | state: merged
34 |
35 | - name: Enable OSPF
36 | ios_config:
37 | lines:
38 | - network 10.99.99.0 0.0.0.255 area 0
39 | - auto-cost reference-bandwidth 1000
40 | parents: router ospf 1
41 |
42 | - name: Enable OSPF
43 | ios_config:
44 | lines:
45 | - int lo1
46 | - ip ospf 1 area 0
47 |
--------------------------------------------------------------------------------
/Ansible/eveng/lab1/group_vars/lab1.yml:
--------------------------------------------------------------------------------
1 | ---
2 | ansible_connection: network_cli
3 | ansible_network_os: ios
4 | ansible_user: knox
5 | ansible_password: cisco
6 | ansible_become: yes
7 | ansible_become_method: enable
8 | ansible_become_password: cisco
--------------------------------------------------------------------------------
/Ansible/eveng/lab1/host_vars/10.10.21.200.yml:
--------------------------------------------------------------------------------
1 | ---
2 | local_loopback:
3 | - name: Loopback1
4 | desc: Sample Ansible config
5 | ip_address: 1.1.1.1/32
6 |
7 | interfaces:
8 | - name: GigabitEthernet0/1
9 | ip_address: 100.100.100.1/30
10 | - name: GigabitEthernet0/2
11 | ip_address: 10.99.99.5/30
12 | - name: GigabitEthernet0/3
13 | ip_address: 10.99.99.9/30
--------------------------------------------------------------------------------
/Ansible/eveng/lab1/host_vars/10.10.21.202.yml:
--------------------------------------------------------------------------------
1 | ---
2 | local_loopback:
3 | - name: Loopback1
4 | desc: Sample Ansible config
5 | ip_address: 2.2.2.2/32
6 |
7 | interfaces:
8 | - name: GigabitEthernet0/1
9 | ip_address: 100.100.100.13/30
10 | - name: GigabitEthernet0/2
11 | ip_address: 10.99.99.17/30
12 | - name: GigabitEthernet0/3
13 | ip_address: 10.99.99.21/30
14 | - name: GigabitEthernet0/4
15 | ip_address: 100.100.100.29/30
--------------------------------------------------------------------------------
/Ansible/eveng/lab1/host_vars/10.10.21.203.yml:
--------------------------------------------------------------------------------
1 | ---
2 | local_loopback:
3 | - name: Loopback1
4 | desc: Sample Ansible config
5 | ip_address: 3.3.3.3/32
6 |
7 | interfaces:
8 | - name: GigabitEthernet0/1
9 | ip_address: 10.99.99.25/30
10 | - name: GigabitEthernet0/2
11 | ip_address: 100.100.100.2/30
12 | - name: GigabitEthernet0/3
13 | ip_address: 100.100.100.14/30
--------------------------------------------------------------------------------
/Ansible/eveng/lab1/host_vars/10.10.21.204.yml:
--------------------------------------------------------------------------------
1 | ---
2 | local_loopback:
3 | - name: Loopback1
4 | desc: Sample Ansible config
5 | ip_address: 4.4.4.4/32
6 |
7 | interfaces:
8 | - name: GigabitEthernet0/1
9 | ip_address: 100.100.100.33/30
10 | - name: GigabitEthernet0/2
11 | ip_address: 10.99.99.37/30
12 | - name: GigabitEthernet0/3
13 | ip_address: 10.99.99.41/30
14 | - name: GigabitEthernet0/4
15 | ip_address: 100.100.100.30/30
--------------------------------------------------------------------------------
/Ansible/eveng/lab1/host_vars/10.10.21.205.yml:
--------------------------------------------------------------------------------
1 | ---
2 | local_loopback:
3 | - name: Loopback1
4 | desc: Sample Ansible config
5 | ip_address: 5.5.5.5/32
6 |
7 | interfaces:
8 | - name: GigabitEthernet0/1
9 | ip_address: 10.99.99.45/30
10 | - name: GigabitEthernet0/2
11 | ip_address: 100.100.100.49/30
12 | - name: GigabitEthernet0/3
13 | ip_address: 100.100.100.34/30
--------------------------------------------------------------------------------
/Ansible/eveng/lab1/host_vars/10.10.21.206.yml:
--------------------------------------------------------------------------------
1 | ---
2 | local_loopback:
3 | - name: Loopback1
4 | desc: Sample Ansible config
5 | ip_address: 6.6.6.6/32
6 |
7 | interfaces:
8 | - name: GigabitEthernet0/1
9 | ip_address: 10.99.99.57/30
10 | - name: GigabitEthernet0/2
11 | ip_address: 10.99.99.61/30
12 | - name: GigabitEthernet0/3
13 | ip_address: 100.100.100.50/30
--------------------------------------------------------------------------------
/Ansible/eveng/lab1/host_vars/10.10.21.207.yml:
--------------------------------------------------------------------------------
1 | ---
2 | local_loopback:
3 | - name: Loopback1
4 | desc: Sample Ansible config
5 | ip_address: 7.7.7.7/32
6 |
7 | interfaces:
8 | - name: GigabitEthernet0/0
9 | ip_address: 10.99.99.6/30
10 | - name: GigabitEthernet0/1
11 | ip_address: 101.101.101.61/30
--------------------------------------------------------------------------------
/Ansible/eveng/lab1/host_vars/10.10.21.208.yml:
--------------------------------------------------------------------------------
1 | ---
2 | local_loopback:
3 | - name: Loopback1
4 | desc: Sample Ansible config
5 | ip_address: 8.8.8.8/32
6 |
7 | interfaces:
8 | - name: GigabitEthernet0/0
9 | ip_address: 10.99.99.62/30
10 | - name: GigabitEthernet0/1
11 | ip_address: 101.101.101.65/30
--------------------------------------------------------------------------------
/Ansible/eveng/lab2/group_vars/lab2.yml:
--------------------------------------------------------------------------------
1 | ---
2 | ansible_connection: network_cli
3 | ansible_network_os: ios
4 | ansible_user: knox
5 | ansible_password: cisco
6 | ansible_become: yes
7 | ansible_become_method: enable
8 | ansible_become_password: cisco
--------------------------------------------------------------------------------
/Ansible/eveng/lab2/host_vars/10.10.21.211.yml:
--------------------------------------------------------------------------------
1 | ---
2 | local_loopback:
3 | - name: Loopback1
4 | desc: Sample Ansible config
5 | ip_address: 1.1.1.1/32
6 |
7 | interfaces:
8 | - name: GigabitEthernet0/0
9 | ip_address: 100.100.100.1/30
--------------------------------------------------------------------------------
/Ansible/eveng/lab2/host_vars/10.10.21.212.yml:
--------------------------------------------------------------------------------
1 | ---
2 | local_loopback:
3 | - name: Loopback1
4 | desc: Sample Ansible config
5 | ip_address: 2.2.2.2/32
6 |
7 | interfaces:
8 | - name: GigabitEthernet0/0
9 | ip_address: 100.100.100.2/30
10 | - name: GigabitEthernet0/1
11 | ip_address: 100.100.100.5/30
12 | - name: GigabitEthernet0/2
13 | ip_address: 105.105.105.1/30
14 | - name: GigabitEthernet0/4
15 | ip_address: 100.100.100.9/30
16 |
--------------------------------------------------------------------------------
/Ansible/eveng/lab2/host_vars/10.10.21.213.yml:
--------------------------------------------------------------------------------
1 | ---
2 | local_loopback:
3 | - name: Loopback1
4 | desc: Sample Ansible config
5 | ip_address: 3.3.3.3/32
6 |
7 | interfaces:
8 | - name: GigabitEthernet0/0
9 | ip_address: 100.100.100.6/30
--------------------------------------------------------------------------------
/Ansible/eveng/lab2/host_vars/10.10.21.214.yml:
--------------------------------------------------------------------------------
1 | ---
2 | local_loopback:
3 | - name: Loopback1
4 | desc: Sample Ansible config
5 | ip_address: 4.4.4.4/32
6 |
7 | interfaces:
8 | - name: GigabitEthernet0/0
9 | ip_address: 105.105.105.2/30
10 | - name: GigabitEthernet0/1
11 | ip_address: 110.110.110.1/30
--------------------------------------------------------------------------------
/Ansible/eveng/lab2/host_vars/10.10.21.215.yml:
--------------------------------------------------------------------------------
1 | ---
2 | local_loopback:
3 | - name: Loopback1
4 | desc: Sample Ansible config
5 | ip_address: 5.5.5.5/32
6 |
7 | interfaces:
8 | - name: GigabitEthernet0/0
9 | ip_address: 110.110.110.2/30
10 | - name: GigabitEthernet0/1
11 | ip_address: 120.120.120.1/30
12 | - name: GigabitEthernet0/2
13 | ip_address: 125.125.125.1/30
--------------------------------------------------------------------------------
/Ansible/eveng/lab2/host_vars/10.10.21.216.yml:
--------------------------------------------------------------------------------
1 | ---
2 | local_loopback:
3 | - name: Loopback1
4 | desc: Sample Ansible config
5 | ip_address: 6.6.6.6/32
6 |
7 | interfaces:
8 | - name: GigabitEthernet0/0
9 | ip_address: 120.120.120.2/30
10 | - name: GigabitEthernet0/1
11 | ip_address: 120.120.120.5/30
--------------------------------------------------------------------------------
/Ansible/eveng/lab2/host_vars/10.10.21.217.yml:
--------------------------------------------------------------------------------
1 | ---
2 | local_loopback:
3 | - name: Loopback1
4 | desc: Sample Ansible config
5 | ip_address: 7.7.7.7/32
6 |
7 | interfaces:
8 | - name: GigabitEthernet0/0
9 | ip_address: 120.120.120.6/30
10 | - name: GigabitEthernet0/1
11 | ip_address: 125.125.125.5/30
--------------------------------------------------------------------------------
/Ansible/eveng/lab2/host_vars/10.10.21.218.yml:
--------------------------------------------------------------------------------
1 | ---
2 | local_loopback:
3 | - name: Loopback1
4 | desc: Sample Ansible config
5 | ip_address: 8.8.8.8/32
6 |
7 | interfaces:
8 | - name: GigabitEthernet0/0
9 | ip_address: 125.125.125.2/30
10 | - name: GigabitEthernet0/1
11 | ip_address: 130.130.130.1/30
--------------------------------------------------------------------------------
/Ansible/eveng/lab2/host_vars/10.10.21.219.yml:
--------------------------------------------------------------------------------
1 | ---
2 | local_loopback:
3 | - name: Loopback1
4 | desc: Sample Ansible config
5 | ip_address: 9.9.9.9/32
6 |
7 | interfaces:
8 | - name: GigabitEthernet0/0
9 | ip_address: 125.125.125.6/30
10 | - name: GigabitEthernet0/1
11 | ip_address: 130.130.130.2/30
12 | - name: GigabitEthernet0/2
13 | ip_address: 140.140.140.1/30
--------------------------------------------------------------------------------
/Ansible/eveng/lab2/host_vars/10.10.21.220.yml:
--------------------------------------------------------------------------------
1 | ---
2 | local_loopback:
3 | - name: Loopback1
4 | desc: Sample Ansible config
5 | ip_address: 10.10.10.10/32
6 |
7 | interfaces:
8 | - name: GigabitEthernet0/0
9 | ip_address: 140.140.140.2/30
--------------------------------------------------------------------------------
/Ansible/eveng/lab2/host_vars/10.10.21.221.yml:
--------------------------------------------------------------------------------
1 | ---
2 | local_loopback:
3 | - name: Loopback1
4 | desc: Sample Ansible config
5 | ip_address: 11.11.11.11/32
6 |
7 | interfaces:
8 | - name: GigabitEthernet0/1
9 | ip_address: 100.100.100.10/30
--------------------------------------------------------------------------------
/Ansible/eveng/lab2/ipv4config.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Address Setup
3 | hosts: lab2
4 | connection: local
5 | gather_facts: no
6 | tasks:
7 | - name: Create Loopback
8 | with_items: "{{local_loopback}}"
9 | ios_interfaces:
10 | config:
11 | - name: "{{item.name}}"
12 | enabled: True
13 | state: merged
14 |
15 | - name: Set Loopback IP
16 | with_items: "{{local_loopback}}"
17 | ios_l3_interface:
18 | name: "{{item.name}}"
19 | ipv4: "{{item.ip_address}}"
20 |
21 | - name: Set Interface IPs
22 | with_items: "{{interfaces}}"
23 | ios_l3_interface:
24 | name: "{{item.name}}"
25 | ipv4: "{{item.ip_address}}"
26 |
27 | - name: No shut
28 | with_items: "{{interfaces}}"
29 | ios_interfaces:
30 | config:
31 | - name: "{{item.name}}"
32 | enabled: True
33 | state: merged
34 |
35 | - name: OSPF setup
36 | hosts: 10.10.21.211,10.10.21.212,10.10.21.213,10.10.21.221
37 | connection: local
38 | gather_facts: no
39 | tasks:
40 | - name: Enable OSPF
41 | ios_config:
42 | lines:
43 | - network 100.100.100.0 0.0.0.255 area 0
44 | - auto-cost reference-bandwidth 1000
45 | parents: router ospf 1
--------------------------------------------------------------------------------
/Ansible/eveng/lab3/group_vars/lab3.yml:
--------------------------------------------------------------------------------
1 | ---
2 | ansible_connection: network_cli
3 | ansible_network_os: ios
4 | ansible_user: knox
5 | ansible_password: cisco
6 | ansible_become: yes
7 | ansible_become_method: enable
8 | ansible_become_password: cisco
--------------------------------------------------------------------------------
/Ansible/eveng/lab3/host_vars/10.10.21.231.yml:
--------------------------------------------------------------------------------
1 | ---
2 | local_loopback:
3 | - name: Loopback1
4 | desc: Sample Ansible config
5 | ip_address: 10.1.1.1/24
6 |
7 | interfaces:
8 | - name: GigabitEthernet0/1
9 | ip_address: 130.130.130.1/30
--------------------------------------------------------------------------------
/Ansible/eveng/lab3/host_vars/10.10.21.232.yml:
--------------------------------------------------------------------------------
1 | ---
2 | local_loopback:
3 | - name: Loopback1
4 | desc: Sample Ansible config
5 | ip_address: 10.1.1.2/24
6 |
7 | interfaces:
8 | - name: GigabitEthernet0/1
9 | ip_address: 130.130.130.5/30
--------------------------------------------------------------------------------
/Ansible/eveng/lab3/host_vars/10.10.21.233.yml:
--------------------------------------------------------------------------------
1 | ---
2 | local_loopback:
3 | - name: Loopback1
4 | desc: Sample Ansible config
5 | ip_address: 172.16.1.3/24
6 |
7 | interfaces:
8 | - name: GigabitEthernet0/1
9 | ip_address: 130.130.130.2/30
10 | - name: GigabitEthernet0/2
11 | ip_address: 130.130.130.6/30
12 | - name: GigabitEthernet0/4
13 | ip_address: 200.200.200.1/30
14 | - name: GigabitEthernet0/3
15 | ip_address: 200.200.200.5/30
--------------------------------------------------------------------------------
/Ansible/eveng/lab3/host_vars/10.10.21.234.yml:
--------------------------------------------------------------------------------
1 | ---
2 | local_loopback:
3 | - name: Loopback1
4 | desc: Sample Ansible config
5 | ip_address: 172.16.1.4/24
6 |
7 | interfaces:
8 | - name: GigabitEthernet0/1
9 | ip_address: 200.200.200.2/30
10 | - name: GigabitEthernet0/2
11 | ip_address: 200.200.200.9/30
--------------------------------------------------------------------------------
/Ansible/eveng/lab3/host_vars/10.10.21.235.yml:
--------------------------------------------------------------------------------
1 | ---
2 | local_loopback:
3 | - name: Loopback1
4 | desc: Sample Ansible config
5 | ip_address: 172.16.1.5/24
6 |
7 | interfaces:
8 | - name: GigabitEthernet0/1
9 | ip_address: 200.200.200.14/30
10 | - name: GigabitEthernet0/2
11 | ip_address: 200.200.200.6/30
--------------------------------------------------------------------------------
/Ansible/eveng/lab3/host_vars/10.10.21.236.yml:
--------------------------------------------------------------------------------
1 | ---
2 | local_loopback:
3 | - name: Loopback1
4 | desc: Sample Ansible config
5 | ip_address: 172.16.1.6/24
6 |
7 | interfaces:
8 | - name: GigabitEthernet0/1
9 | ip_address: 200.200.200.14/30
10 | - name: GigabitEthernet0/2
11 | ip_address: 200.200.200.10/30
12 | - name: GigabitEthernet0/3
13 | ip_address: 205.205.205.1/30
--------------------------------------------------------------------------------
/Ansible/eveng/lab3/host_vars/10.10.21.237.yml:
--------------------------------------------------------------------------------
1 | ---
2 | local_loopback:
3 | - name: Loopback1
4 | desc: Sample Ansible config
5 | ip_address: 192.168.1.7/24
6 |
7 | interfaces:
8 | - name: GigabitEthernet0/1
9 | ip_address: 205.205.205.2/30
10 | - name: GigabitEthernet0/2
11 | ip_address: 100.100.100.5/30
12 | - name: GigabitEthernet0/3
13 | ip_address: 100.100.100.1/30
--------------------------------------------------------------------------------
/Ansible/eveng/lab3/host_vars/10.10.21.238.yml:
--------------------------------------------------------------------------------
1 | ---
2 | local_loopback:
3 | - name: Loopback1
4 | desc: Sample Ansible config
5 | ip_address: 192.168.1.8/24
6 |
7 | interfaces:
8 | - name: GigabitEthernet0/1
9 | ip_address: 100.100.100.9/30
10 | - name: GigabitEthernet0/2
11 | ip_address: 100.100.100.2/30
12 |
--------------------------------------------------------------------------------
/Ansible/eveng/lab3/host_vars/10.10.21.239.yml:
--------------------------------------------------------------------------------
1 | ---
2 | local_loopback:
3 | - name: Loopback1
4 | desc: Sample Ansible config
5 | ip_address: 192.168.1.9/24
6 |
7 | interfaces:
8 | - name: GigabitEthernet0/1
9 | ip_address: 100.100.100.6/30
10 | - name: GigabitEthernet0/2
11 | ip_address: 100.100.100.13/30
12 |
--------------------------------------------------------------------------------
/Ansible/eveng/lab3/host_vars/10.10.21.240.yml:
--------------------------------------------------------------------------------
1 | ---
2 | local_loopback:
3 | - name: Loopback1
4 | desc: Sample Ansible config
5 | ip_address: 192.168.1.10/24
6 |
7 | interfaces:
8 | - name: GigabitEthernet0/1
9 | ip_address: 100.100.100.14/30
10 | - name: GigabitEthernet0/2
11 | ip_address: 100.100.100.10/30
12 |
--------------------------------------------------------------------------------
/Ansible/eveng/lab3/lab3config.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Address Setup
3 | hosts: lab3
4 | connection: local
5 | gather_facts: no
6 | tasks:
7 | - name: Create Loopback
8 | with_items: "{{local_loopback}}"
9 | ios_interfaces:
10 | config:
11 | - name: "{{item.name}}"
12 | enabled: True
13 | state: merged
14 |
15 | - name: Set Loopback IP
16 | with_items: "{{local_loopback}}"
17 | ios_l3_interface:
18 | name: "{{item.name}}"
19 | ipv4: "{{item.ip_address}}"
20 |
21 | - name: Set Interface IPs
22 | with_items: "{{interfaces}}"
23 | ios_l3_interface:
24 | name: "{{item.name}}"
25 | ipv4: "{{item.ip_address}}"
26 |
27 | - name: No shut
28 | with_items: "{{interfaces}}"
29 | ios_interfaces:
30 | config:
31 | - name: "{{item.name}}"
32 | enabled: True
33 | state: merged
--------------------------------------------------------------------------------
/Ansible/iosxe/facts.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Gather IOS-XE Facts
3 | hosts: sandbox
4 | connection: local
5 | tasks:
6 | - name: Gather IOS Facts
7 | ios_facts:
8 | provider:
9 | host: ios-xe-mgmt-latest.cisco.com
10 | port: 8181
11 | username: root
12 | password: D_Vay!_10&
13 |
14 | - name: What is the IOS OS ver?
15 | debug:
16 | var: ansible_net_version
17 |
18 | - name: What is the hostname?
19 | debug:
20 | var: ansible_net_hostname
21 | #### OTHER USEFUL VARS
22 | # ansible_net_config - this gets the running config
23 | # ansible_net_model
24 | # ansible_net_serialnum
25 | # ansible_net_image
26 | # ansible_net_all_ipv4_addresses
27 | # ansible_net_all_ipv6_addresses
28 | # ansible_net_neighbors
29 | # ansible_net_interfaces
30 | # ansible_net_memfree_mb
31 | # ansible_net_memtotal_mb
32 |
--------------------------------------------------------------------------------
/Ansible/iosxe/show.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Issue show commands
3 | hosts: sandbox
4 | connection: local
5 | tasks:
6 | - name: Show ip int brief
7 | ios_command:
8 | commands:
9 | - show ip int brief
10 | provider:
11 | host: ios-xe-mgmt-latest.cisco.com
12 | port: 8181
13 | authorize: yes
14 | username: root
15 | password: D_Vay!_10&
16 | register: if_data
17 |
18 | - name: Interfaces output
19 | debug:
20 | var: if_data['stdout_lines'][0]
21 |
--------------------------------------------------------------------------------
/Ansible/networking/.ansible_env:
--------------------------------------------------------------------------------
1 | export ANSIBLE_NET_USERNAME=cisco
2 | export ANSIBLE_NET_PASSWORD=cisco
3 | export ANSIBLE_CONNECTION=local
--------------------------------------------------------------------------------
/Ansible/networking/delLoop.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Delete Loopbacks on device
3 | hosts: switches
4 | connection: local
5 | tasks:
6 | - name: Del loopback shell
7 | with_items: "{{local_loopback}}"
8 | nxos_interface:
9 | interface: "{{item.name}}"
10 | state: absent
11 |
--------------------------------------------------------------------------------
/Ansible/networking/group_vars/switches.yml:
--------------------------------------------------------------------------------
1 | ansible_connection: network_cli
2 | ansible_network_os: nxos
3 | ansible_user: cisco
4 | ansible_password: cisco
5 |
6 |
--------------------------------------------------------------------------------
/Ansible/networking/host_vars/172.16.1.4.yml:
--------------------------------------------------------------------------------
1 | ---
2 | local_loopback:
3 | - name: Loopback1
4 | desc: Sample Ansible config
5 | ip_address: 172.20.1.2/24
6 | - name: Loopback2
7 | desc: Sample Ansible config
8 | ip_address: 172.22.1.2/24
9 | - name: Loopback3
10 | desc: Sample Ansible config
11 | ip_address: 172.24.1.2/24
12 |
13 |
--------------------------------------------------------------------------------
/Ansible/networking/host_vars/172.16.1.68.yml:
--------------------------------------------------------------------------------
1 | ---
2 | local_loopback:
3 | - name: Loopback1
4 | desc: Sample Ansible config
5 | ip_address: 172.20.1.3/24
6 | - name: Loopback2
7 | desc: Sample Ansible config
8 | ip_address: 172.22.1.3/24
9 | - name: Loopback3
10 | desc: Sample Ansible config
11 | ip_address: 172.24.1.3/24
12 |
--------------------------------------------------------------------------------
/Ansible/networking/loopback.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Create Loopbacks on device
3 | hosts: switches
4 | connection: local
5 | gather_facts: no
6 | tasks:
7 | - name: Create loopback shell
8 | with_items: "{{local_loopback}}"
9 | nxos_interface:
10 | interface: "{{item.name}}"
11 | mode: layer3
12 | description: "{{item.desc}}"
13 | admin_state: up
14 |
15 | - name: Set new loopback configs
16 | with_items: "{{local_loopback}}"
17 | nxos_l3_interfaces:
18 | config:
19 | - name: "{{item.name}}"
20 | ipv4:
21 | - address: "{{item.ip_address}}"
22 | state: merged
23 |
--------------------------------------------------------------------------------
/Ansible/networking/network.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: 9k facts
3 | hosts: 172.16.1.68
4 | connection: local
5 | tasks:
6 | - name: Get Nexus9k facts
7 | nxos_facts:
8 | host: "{{inventory_hostname}}"
9 | transport: nxapi
10 | use_ssl: yes
11 | validate_certs: no
12 | register: nxos_data
13 |
14 | - name: Print name to console
15 | debug: msg="{{nxos_data}}"
16 |
--------------------------------------------------------------------------------
/Ansible/restconf/files/ietf_inteface.j2:
--------------------------------------------------------------------------------
1 | {
2 | "interface": {
3 | "name": "{{item.name}}",
4 | "description": "{{item.desc}}",
5 | "type": "iana-if-type:softwareLoopback",
6 | "enabled": true,
7 | "ietf-ip:ipv4": {
8 | "address": [
9 | {
10 | "ip": "{{item.ip_address}}",
11 | "netmask": "{{item.prefix}}"
12 | }
13 | ]
14 | }
15 | }
16 | }
--------------------------------------------------------------------------------
/Ansible/restconf/host_vars/172.16.1.25.yml:
--------------------------------------------------------------------------------
1 | ---
2 | ansible_connection: "httpapi"
3 | ansible_network_os: "restconf"
4 | ansible_httpapi_use_ssl: true
5 | ansible_httpapi_port: 443
6 | ansible_httpapi_validate_certs: false
7 | ansible_httpapi_restconf_root: "/restconf"
8 | ansible_user: "cisco"
9 | ansible_password: "cisco"
10 |
11 | local_loopback:
12 | - name: "Loopback100"
13 | desc: "Created by Ansible"
14 | ip_address: 10.99.99.1
15 | prefix: 255.255.255.0
16 |
17 | new_loop:
18 | interface:
19 | - name: "Loopback100"
20 | type: "iana-if-type:softwareLoopback"
21 | enabled: true
22 | ietf-ip:ipv4:
23 | address:
24 | - ip: 10.99.99.1
25 | netmask: 255.255.255.0
26 |
--------------------------------------------------------------------------------
/Ansible/restconf/host_vars/ios-xe-mgmt-latest.cisco.com.yml:
--------------------------------------------------------------------------------
1 | ---
2 | ansible_connection: "httpapi"
3 | ansible_network_os: "restconf"
4 | ansible_httpapi_use_ssl: true
5 | ansible_httpapi_port: 9443
6 | ansible_httpapi_validate_certs: false
7 | ansible_httpapi_restconf_root: "/restconf"
8 | ansible_user: "root"
9 | ansible_password: "D_Vay!_10&"
10 |
11 | local_loopback:
12 | - name: "Loopback102"
13 | desc: "Created by Ansible"
14 | ip_address: 10.99.99.1
15 | prefix: 255.255.255.0
16 |
17 | new_loop:
18 | interface:
19 | - name: "Loopback102"
20 | type: "iana-if-type:softwareLoopback"
21 | enabled: true
22 | ietf-ip:ipv4:
23 | address:
24 | - ip: 10.99.99.1
25 | prefix: 255.255.255.0
26 |
--------------------------------------------------------------------------------
/Ansible/restconf/jinja.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Create loopback payload from template
3 | hosts: 172.16.1.25
4 | connection: local
5 |
6 | tasks:
7 | - name: Create template
8 | with_items: "{{local_loopback}}"
9 | template: src="files/ietf_inteface.j2" dest="./output.json"
--------------------------------------------------------------------------------
/Ansible/restconf/output.json:
--------------------------------------------------------------------------------
1 | {
2 | "interface": {
3 | "name": "Loopback102",
4 | "description": "Created by Ansible",
5 | "type": "iana-if-type:softwareLoopback",
6 | "enabled": true,
7 | "ietf-ip:ipv4": {
8 | "address": [
9 | {
10 | "ip": "10.99.99.1",
11 | "netmask": "255.255.255.0"
12 | }
13 | ]
14 | }
15 | }
16 | }
--------------------------------------------------------------------------------
/Ansible/restconf/restconf_config.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Create loopback payload from template
3 | hosts: sandbox
4 | connection: local
5 |
6 | tasks:
7 | - name: Create template
8 | with_items: "{{local_loopback}}"
9 | template: src="files/ietf_inteface.j2" dest="./output.json"
10 |
11 | - name: Create loopbacks with RESTCONF
12 | with_items: "{{local_loopback}}"
13 | restconf_config:
14 | method: post
15 | format: json
16 | path: /data/ietf-interfaces:interfaces
17 | #content: "{{ new_loop | to_json }}"
18 | content: "{{ lookup('file','./output.json') | string }}"
19 | register: results
20 | ignore_errors: true
21 |
22 | - name: print output
23 | debug: msg="{{results}}"
24 |
25 | # - name: Delete interface
26 | # with_items: "{{local_loopback}}"
27 | # restconf_config:
28 | # method: delete
29 | # format: json
30 | # path: "/data/ietf-interfaces:interfaces/interface={{item.name}}"
31 |
--------------------------------------------------------------------------------
/Ansible/restconf/restconf_get.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Create loopback payload from template
3 | hosts: sandbox
4 | connection: local
5 | tasks:
6 | - name: Get some configs
7 | restconf_get:
8 | content: config
9 | output: json
10 | path: /data/ietf-interfaces:interfaces
11 | register: dataout
12 |
13 | - name: print output
14 | debug: msg="{{dataout}}"
15 |
--------------------------------------------------------------------------------
/Postman/DNA/DNA.postman_environment.json:
--------------------------------------------------------------------------------
1 | {
2 | "id": "1e3d644b-726a-470e-9f4e-23d11648b5c0",
3 | "name": "DNA",
4 | "values": [
5 | {
6 | "key": "dna",
7 | "value": "sandboxdnac2.cisco.com",
8 | "enabled": true
9 | },
10 | {
11 | "key": "token",
12 | "value": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiI1Y2U3MTJiMDhlZTY2MjAyZmEyZWI4ZjgiLCJhdXRoU291cmNlIjoiaW50ZXJuYWwiLCJ0ZW5hbnROYW1lIjoiVE5UMCIsInJvbGVzIjpbIjViNmNmZGZmNDMwOTkwMDA4OWYwZmYzNyJdLCJ0ZW5hbnRJZCI6IjViNmNmZGZjNDMwOTkwMDA4OWYwZmYzMCIsImV4cCI6MTU3OTk3NTQ5OSwiaWF0IjoxNTc5OTcxODk5LCJqdGkiOiIyZWVmNWM1MS01Zjc5LTQ2NzQtYTlhMy1kOGNkMmY0ZTg2ZTQiLCJ1c2VybmFtZSI6ImRldm5ldHVzZXIifQ.Zzx8lHAgz4oKUKFEN9f2iDvb_UuMwnSXevQIloxnu9Y8Zx9e8-GpV0PciVM51P6oufJeswlE0oWSePKQhiR2LFQoDZmJnztBluM6gnxRv1lcVicSQIFeQnJ01kf86nMY5OA2Zl4oNO6AvY6aZgiJoJyOmeAEMnIKDGxvirqyA1vJuPoywJBQlOOd0l32pG9aq2B9cq3UtEKZaF54AEenLzlKq2yc8ffMx-cStSV6PwuH-n_8qcg5oXSfYf0Ndbe5WuSCPFuUesvCTmpQI_eXZJDIlMmJ0EMyYMr8FSY6IjOtL_vmX52EcpGQgAdyegqeuX7VqG25qdF475rx1BHn-w",
13 | "enabled": true
14 | },
15 | {
16 | "key": "user",
17 | "value": "devnetuser",
18 | "enabled": true
19 | },
20 | {
21 | "key": "pw",
22 | "value": "Cisco123!",
23 | "enabled": true
24 | },
25 | {
26 | "key": "net_dev_id",
27 | "value": "50c96308-84b5-43dc-ad68-cda146d80290",
28 | "enabled": true
29 | }
30 | ],
31 | "_postman_variable_scope": "environment",
32 | "_postman_exported_at": "2020-01-25T18:10:02.064Z",
33 | "_postman_exported_using": "Postman/7.16.1"
34 | }
--------------------------------------------------------------------------------
/Postman/IOS-XE/IOS-XE.postman_environment.json:
--------------------------------------------------------------------------------
1 | {
2 | "id": "24aa2b67-7c2f-4792-8728-ee9c006c2fc6",
3 | "name": "IOS-XE",
4 | "values": [
5 | {
6 | "key": "h",
7 | "value": "ios-xe-mgmt-latest.cisco.com",
8 | "enabled": true
9 | },
10 | {
11 | "key": "p",
12 | "value": "9443",
13 | "enabled": true
14 | },
15 | {
16 | "key": "username",
17 | "value": "root",
18 | "enabled": true
19 | },
20 | {
21 | "key": "password",
22 | "value": "D_Vay!_10&",
23 | "enabled": true
24 | }
25 | ],
26 | "_postman_variable_scope": "environment",
27 | "_postman_exported_at": "2020-03-19T14:22:32.914Z",
28 | "_postman_exported_using": "Postman/7.20.1"
29 | }
--------------------------------------------------------------------------------
/Postman/Meraki/Meraki.postman_environment.json:
--------------------------------------------------------------------------------
1 | {
2 | "id": "a271bdaf-ed4c-42cd-93e5-42334f117c8a",
3 | "name": "Meraki",
4 | "values": [
5 | {
6 | "key": "X-Cisco-Meraki-API-Key",
7 | "value": "6bec40cf957de430a6f1f2baa056b99a4fac9ea0",
8 | "enabled": true
9 | },
10 | {
11 | "key": "Organization Name",
12 | "value": "DevNet Sandbox",
13 | "enabled": true
14 | },
15 | {
16 | "key": "Network Name",
17 | "value": "DNSMB5",
18 | "enabled": true
19 | },
20 | {
21 | "key": "organizationId",
22 | "value": "549236",
23 | "enabled": true
24 | },
25 | {
26 | "key": "networkId",
27 | "value": "L_646829496481104447",
28 | "enabled": true
29 | }
30 | ],
31 | "_postman_variable_scope": "environment",
32 | "_postman_exported_at": "2020-03-13T16:07:23.880Z",
33 | "_postman_exported_using": "Postman/7.19.1"
34 | }
--------------------------------------------------------------------------------
/Powershell/Networking/RESTCONF.ps1:
--------------------------------------------------------------------------------
1 | $uri = 'https://ios-xe-mgmt.cisco.com:9443/restconf/data/Cisco-IOS-XE-interfaces-oper:interfaces/interface=GigabitEthernet1'
2 | # $creds = Get-Credential #root D_Vay!_10&
3 | $password = ConvertTo-SecureString 'D_Vay!_10&' -AsPlainText -Force
4 | $Cred = New-Object System.Management.Automation.PSCredential ('root', $password)
5 | $headers = @{'Accept' = 'application/yang-data+json' }
6 |
7 | $response = Invoke-RestMethod -Uri $uri `
8 | -Method Get `
9 | -Authentication Basic `
10 | -Credential $Cred `
11 | -ContentType 'application/yang-data+json' `
12 | -Headers $headers `
13 | -SkipCertificateCheck
14 |
15 | $response | ConvertTo-Json | Write-Output
16 |
17 | $response.'Cisco-IOS-XE-interfaces-oper:interface'.name
18 |
19 | if ($response.'Cisco-IOS-XE-interfaces-oper:interface'.'admin-status' -eq 'if-state-up') {
20 | Write-Host ($response.'Cisco-IOS-XE-interfaces-oper:interface'.name)'is up'
21 | }
22 |
--------------------------------------------------------------------------------
/Powershell/Networking/aci.ps1:
--------------------------------------------------------------------------------
1 | $url = "https://sandboxapicdc.cisco.com:443/api/aaaLogin.json"
2 | $payload = @{
3 | aaaUser = @{
4 | attributes = @{
5 | name = "admin"
6 | pwd = "ciscopsdt"
7 | }
8 | }
9 | }
10 |
11 | $headers = @{'Accept' = 'application/json' }
12 |
13 | $response = Invoke-RestMethod -Uri $url `
14 | -Method post `
15 | -Body ($payload | ConvertTo-Json) `
16 | -ContentType 'application/json' `
17 | -Headers $headers `
18 | -SkipCertificateCheck `
19 | -SessionVariable s
20 | # Print token
21 | Write-Host "Token: " -ForegroundColor Red -NoNewline
22 | Write-Host $response.imdata.aaaLogin.attributes.token
23 |
24 | $uri = "https://sandboxapicdc.cisco.com:443/api/node/mo/uni/tn-Heroes/ap-Save_The_Planet.json"
25 |
26 | $ap = Invoke-RestMethod -Uri $uri `
27 | -Method Get `
28 | -ContentType 'application/json' `
29 | -Headers $headers `
30 | -SkipCertificateCheck `
31 | -Websession $s
32 | Write-Host "App: " -ForegroundColor Red
33 | $ap.imdata.fvAp.attributes
--------------------------------------------------------------------------------
/Powershell/Networking/dna.ps1:
--------------------------------------------------------------------------------
1 | $url = "https://sandboxdnac2.cisco.com/dna/system/api/v1/auth/token"
2 |
3 | $user = 'devnetuser'
4 | $pw = ConvertTo-SecureString 'Cisco123!' -AsPlainText -Force
5 | $Cred = New-Object System.Management.Automation.PSCredential ($user, $pw)
6 |
7 | $headers = @{'Accept' = 'application/json' }
8 |
9 | $response = Invoke-RestMethod -Uri $url `
10 | -Method post `
11 | -Authentication Basic `
12 | -Credential $Cred `
13 | -ContentType 'application/json' `
14 | -Headers $headers `
15 | -SkipCertificateCheck
16 |
17 |
18 | $response | ConvertTo-Json | Write-Output
19 | $token = $response.token
20 |
21 | $url = "https://sandboxdnac2.cisco.com/dna/intent/api/v1/client-health?timestamp="
22 | $headers = @{
23 | 'Accept' = 'application/json'
24 | 'X-auth-token' = $token
25 | }
26 |
27 | $response = Invoke-RestMethod -Uri $url `
28 | -Method get `
29 | -Authentication Basic `
30 | -Credential $Cred `
31 | -ContentType 'application/json' `
32 | -Headers $headers `
33 | -SkipCertificateCheck
34 |
35 | $details = $response.response.scoreDetail
36 | ForEach ($detail in $details) {
37 | Write-Host "Object " -ForegroundColor Blue -NoNewline
38 | Write-Host "$($detail.scoreCategory.value)" -ForegroundColor Red
39 | }
--------------------------------------------------------------------------------
/Powershell/Networking/meraki.ps1:
--------------------------------------------------------------------------------
1 | $url = "https://dashboard.meraki.com/api/v0/organizations"
2 | $headers = @{
3 | 'Accept' = 'application/json'
4 | 'X-Cisco-Meraki-API-Key' = "6bec40cf957de430a6f1f2baa056b99a4fac9ea0"
5 | }
6 |
7 | $orgs = Invoke-RestMethod -Uri $url `
8 | -Method get `
9 | -ContentType 'application/json' `
10 | -Headers $headers
11 |
12 | ForEach ($org in $orgs) {
13 | If ($org.name -eq 'DevNet Sandbox') {
14 | $orgId = $org.id
15 | }
16 | }
17 | $orgId
18 | $net_url = "https://dashboard.meraki.com/api/v0/organizations/$($orgId)/networks"
19 | $networks = Invoke-RestMethod -Uri $net_url `
20 | -Method get `
21 | -ContentType 'application/json' `
22 | -Headers $headers
23 |
24 | ForEach ($network in $networks) {
25 | #Write-Host $network.name
26 | If ($network.name -eq 'DNSMB5') {
27 | $netId = $network.id
28 | }
29 | }
30 |
31 | $devices_url = "https://dashboard.meraki.com/api/v0/networks/$($netId)/devices"
32 | $devices = Invoke-RestMethod -Uri $devices_url `
33 | -Method get `
34 | -ContentType 'application/json' `
35 | -Headers $headers
36 |
37 | $devices | ConvertTo-Json | Write-Output
--------------------------------------------------------------------------------
/Powershell/Networking/sdwan.ps1:
--------------------------------------------------------------------------------
1 | $url = 'https://sandboxsdwan.cisco.com:8443/j_security_check'
2 | $login_body = @{
3 | j_username = 'devnetuser'
4 | j_password = 'Cisco123!'
5 | }
6 |
7 | $headers = @{'Accept' = 'application/json' }
8 |
9 | #$response = `
10 | Invoke-RestMethod -Uri $url `
11 | -Method post `
12 | -Body ($login_body) `
13 | -ContentType 'application/x-www-form-urlencoded' `
14 | -Headers $headers `
15 | -SkipCertificateCheck `
16 | -SessionVariable s
17 | #$response
18 |
19 | $uri = 'https://sandboxsdwan.cisco.com:8443/dataservice/device'
20 | $devs = Invoke-RestMethod -Uri $uri `
21 | -Method Get `
22 | -ContentType 'application/json' `
23 | -Headers $headers `
24 | -SkipCertificateCheck `
25 | -Websession $s
26 |
27 | Write-Host "Output!!!!!!!"
28 | $devices = $devs.data
29 | ForEach ($device in $devices) {
30 | write-host $device
31 | }
--------------------------------------------------------------------------------
/Powershell/Networking/ubnt.ps1:
--------------------------------------------------------------------------------
1 | $uri = 'https://IP OR FQDN:8443/api/login'
2 | $headers = @{'Accept' = 'application/json' }
3 | $params = @{
4 | 'username' = 'USER';
5 | 'password' = 'PASSWORD';
6 | }
7 | $body = $params | ConvertTo-Json
8 |
9 | $response = Invoke-RestMethod -Uri $uri `
10 | -Body $body `
11 | -Method Post `
12 | -ContentType 'application/json' `
13 | -Headers $headers `
14 | -SkipCertificateCheck `
15 | -SessionVariable s
16 |
17 |
18 | #$response | ConvertTo-Json | Write-Output
19 |
20 | $uri = 'https://IP OR FQDN:8443/api/self/sites'
21 | $sites = Invoke-RestMethod -Uri $uri `
22 | -Method Get `
23 | -ContentType 'application/json' `
24 | -Headers $headers `
25 | -SkipCertificateCheck `
26 | -Websession $s
27 |
28 | #$sites | ConvertTo-Json | Write-Output
29 |
30 | $siteData = $sites.data
31 | $name = $siteData | Where-Object { $_.desc -eq 'Knox-Home' } | Select-Object name
32 |
33 | $uri = "https://IP OR FQDN:8443/api/s/$($name.name)/stat/device"
34 | $devices = Invoke-RestMethod -Uri $uri `
35 | -Method Get `
36 | -ContentType 'application/json' `
37 | -Headers $headers `
38 | -SkipCertificateCheck `
39 | -Websession $s
40 |
41 | $devices | ConvertTo-Json | Write-Output
--------------------------------------------------------------------------------
/Powershell/Networking/ucs.ps1:
--------------------------------------------------------------------------------
1 | Connect-Ucs -Name '10.10.20.113'
2 |
3 | Get-UcsBlade
4 |
5 | Get-UcsBlade | Select-Object Dn
6 |
7 | Get-UcsBlade | Select-Object Dn, TotalMemory, NumOfCpus, Serial
--------------------------------------------------------------------------------
/Powershell/Powershell7/ActiveDirectory/ADGroups.ps1:
--------------------------------------------------------------------------------
1 | # Get Groups
2 | Get-AdGroup -Filter *
3 | Get-ADGroup -Filter 'GroupCategory -eq "Security" -and GroupScope -ne "DomainLocal"'
4 |
5 | Get-AdGroup -Identity "Domain Admins"
6 | # Get Members in a group
7 | Get-AdGroup -Identity "Domain Admins" | Get-AdGroupMember
8 | # New OU
9 | New-ADOrganizationalUnit -Name "Groups" -Path "OU=Users,OU=Accounts,DC=nuggetlab,DC=com"
10 | # New Group
11 | New-ADGroup -Name "App Admins" -SamAccountName appAdmins -GroupCategory security -GroupScope Global -DisplayName "App Admins" -Path "OU=Groups,OU=Users,OU=Accounts,DC=nuggetlab,DC=com"
12 | # Add Members to group d
13 | Add-AdGroupMember -Identity appAdmins -Members candy.spoon
--------------------------------------------------------------------------------
/Powershell/Powershell7/ActiveDirectory/PSDrive.ps1:
--------------------------------------------------------------------------------
1 | Get-PsDrive
2 | #Explore the Drive
3 | Get-ChildItem AD:
4 | #Explore Active Directory
5 | Get-ChildItem "DC=nuggetlab,DC=com"
6 |
7 | #Explore OUs
8 | Get-ChildItem "OU=Users,OU=Accounts,DC=nuggetlab,DC=com"
--------------------------------------------------------------------------------
/Powershell/Powershell7/ActiveDirectory/Users.ps1:
--------------------------------------------------------------------------------
1 | Get-AdUser -Identity candy.spoon
2 | #Pipeline operations
3 | Get-AdUser -Identity candy.spoon | Disable-AdAccount
4 |
5 | #Get all Users in a specific OU
6 | Get-AdUser -Filter 'Name -like "*"' -SearchBase "OU=Users,OU=Accounts,DC=nuggetlab,DC=com"
7 |
8 | New-AdUser -Name "Knox Hutchinson" -GivenName "Knox" -Surname "Hutchinson" -SamAccountName "khutchinson" -UserPrincipalName "khutchinson@nuggetlab.com" -AccountPassword (ConvertTo-SecureString -AsPlainText "M!yurtfe777" -Force) -Path "OU=Users,OU=Accounts,DC=nuggetlab,DC=com" -Enabled $True -OtherAttributes @{'mail' = 'khutchinson@nuggetlab.com' }
9 |
10 | Get-AdUser khutchinson | Set-ADUser -ChangePasswordAtLogon $True
--------------------------------------------------------------------------------
/Powershell/Powershell7/ActiveDirectory/userprops.ps1:
--------------------------------------------------------------------------------
1 | # Does this work?
2 | Set-AdAccountPassword -Identity candy.spoon -NewPassword (ConvertTo-SecureString -AsPlainText "MyPw!22222aaaa" -Force)
3 |
4 | #Why did this work?
5 | Set-AdAccountPassword -Identity candy.spoon -NewPassword (ConvertTo-SecureString -AsPlainText "MyPw!22222aaaa" -Force) -Reset
6 |
7 | #Look at the Identity Property - what object type does it take?
8 | Set-AdAccountPassword -Identity
9 |
10 | Get-AdUser -Identity candy.spoon
11 |
12 | Get-AdUser -Identity candy.spoon | Select-Object *
13 |
14 | $candy = Get-AdUser -Identity candy.spoon | Select-Object *
15 | $candy
16 | $candy.PropertyNames
--------------------------------------------------------------------------------
/Powershell/Powershell7/Azure/connect.ps1:
--------------------------------------------------------------------------------
1 | Connect-AzAccount
2 |
3 | Get-AzSubscription
4 |
5 | Get-AzSubscription | Where-Object { $_.Name -eq "Knoxs" } | Select-AzSubscription
6 |
7 | Get-AzResourceGroup
8 |
9 | $rg = Get-AzResourceGroup -Name "knoxsdata"
10 |
11 | Get-AzResource -ResourceGroupName $rg.ResourceGroupName
12 |
13 | Get-AzResource -ResourceGroupName $(Get-AzResourceGroup -Name "knoxsdata").ResourceGroupName
--------------------------------------------------------------------------------
/Powershell/Powershell7/Azure/networks.ps1:
--------------------------------------------------------------------------------
1 | #Connect-AzAccount
2 |
3 | Get-AzSubscription | Where-Object { $_.Name -like "Pay-As-You-Go" } | Select-AzSubscription
4 | Get-AzVirtualNetwork -ResourceGroupName appdev
5 | #$vnet = Get-AzVirtualNetwork -ResourceGroupName appdev
6 | #$vnet.SubnetsText | ConvertFrom-Json
7 | Get-AzNetworkSecurityGroup -ResourceGroup appdev
--------------------------------------------------------------------------------
/Powershell/Powershell7/Azure/rgs.ps1:
--------------------------------------------------------------------------------
1 | Connect-AzAccount
2 |
3 | Get-AzSubscription | Where-Object { $_.Name -like "Pay-As-You-Go" } | Select-AzSubscription
4 |
5 | Get-AzResourceGroup | Where-Object { $_.ResourceGroupName -like '*Posh*' }
6 |
7 | New-AzResourceGroup -Name MadeByPosh -Location 'Central US'
8 |
9 | Get-AzResourceGroup | FT
10 |
11 | Get-AzResource -ResourceGroupName 'MadeByPosh'
--------------------------------------------------------------------------------
/Powershell/Powershell7/Azure/shutdown.ps1:
--------------------------------------------------------------------------------
1 | #Connect-AzAccount
2 |
3 | Get-AzSubscription | Where-Object { $_.Name -like "Pay-as-you-Go" } | Select-AzSubscription
4 | Write-Host "$(Get-Date): Printing list of RGs"
5 | Get-AzResourceGroup
6 |
7 | $rg = Read-Host -Prompt "Which Resource Group would you like to disable?"
8 |
9 | $rgContext = Get-AzResourceGroup -Name $rg
10 |
11 | Write-Host "$(Get-Date): Getting VMs"
12 |
13 | $vms = Get-AzVm -Status
14 |
15 | foreach ($vm in $vms) {
16 | if ($vm.PowerState -like "*running*") {
17 | Write-Host "$(Get-Date): $($vm.Name) is running. Stopping"
18 | $vm | Stop-AzVm -Force -NoWait
19 | Write-Host "$(Get-Date): $($vm.Name) is stopping"
20 | }
21 | }
--------------------------------------------------------------------------------
/Powershell/Powershell7/Azure/vms.ps1:
--------------------------------------------------------------------------------
1 | Connect-AzAccount
2 |
3 | Get-AzSubscription | Where-Object { $_.Name -like "Pay-As-You-Go" } | Select-AzSubscription
4 |
5 | New-AzVM -Name PoshVm `
6 | -ResourceGroupName $(Get-AzResourceGroup | Where-Object { $_.ResourceGroupName -like '*Posh' }).ResourceGroupName `
7 | -Credential (Get-Credential) `
8 | -Location 'Central US' `
9 | -Image UbuntuLTS
10 |
11 | $vm = Get-AzVm -Name PoshVm -ResourceGroupName MadeByPosh
12 |
13 | $vm
14 |
15 | $vm | Get-AzPublicIpAddress
16 |
17 | $vm | Stop-AzVmss
18 |
19 | <#
20 | Other useful cmdlets
21 | Start-AzVm
22 | Restart-AzVm
23 | Remove-AzVm
24 |
25 | #>
--------------------------------------------------------------------------------
/Powershell/Powershell7/CommonTasks/email.ps1:
--------------------------------------------------------------------------------
1 |
2 | <#
3 | https://www.siteground.com/kb/google_free_smtp_server/
4 | Outgoing Mail (SMTP) Server: smtp.gmail.com
5 | Use Authentication: Yes
6 | Use Secure Connection: Yes (TLS or SSL depending on your mail client/website SMTP plugin)
7 | Username: your Gmail account (e.g. user@gmail.com)
8 | Password: your Gmail password
9 | Port: 465 (SSL required) or 587 (TLS required)
10 | #>
11 |
12 | Send-MailMessage -From 'knox.hutchinson@cbtnuggets.com'`
13 | -To 'knox@knoxsdata.com' `
14 | -Subject 'Data Knox YouTube Channel' `
15 | -Body "Go check it out - https://youtube.com/c/Dataknox" `
16 | -Attachments .\data.csv `
17 | -Priority High `
18 | -DeliveryNotificationOption OnSuccess, OnFailure `
19 | -SmtpServer 'smtp.gmail.com' `
20 | -Port 587 `
21 | -UseSsl `
22 | -Credential (Get-Credential)
23 |
--------------------------------------------------------------------------------
/Powershell/Powershell7/CommonTasks/jobs.ps1:
--------------------------------------------------------------------------------
1 | #Block your process
2 | $i = 1
3 | while ($True) {
4 | $i++
5 | $i
6 | Start-Sleep 5
7 | }
8 | # Start a job
9 | Start-Job -ScriptBlock {
10 | $i = 1
11 | while ($True) {
12 | $i++
13 | $i
14 | Start-Sleep 5
15 | }
16 | }
17 | # Details
18 | Get-Job Job1
19 | Receive-Job Job1
20 | Stop-Job Job1
21 | #Job parameter
22 | Invoke-Command dc-nug { Get-Service } -AsJob
--------------------------------------------------------------------------------
/Powershell/Powershell7/CommonTasks/remoting.ps1:
--------------------------------------------------------------------------------
1 | Enable-PSRemoting
2 |
3 | #Remotely enter a computer
4 | Enter-PSSession
5 | Get-Service
6 | Exit-PSSession
7 |
8 | #Run commands remotely
9 | Invoke-Command dc-nug { Get-Service }
10 |
11 | #Run GP Updates
12 | Invoke-GPUpdate dc-nug
13 | Get-ADComputer -Filter * | ForEach-Object { Invoke-GpUpdate -Computer $_.name -Force }
14 |
15 | ##### LINUX
16 | <#
17 | sudo apt install openssh-client
18 | sudo apt install openssh-server
19 | nano /etc/ssh/sshd_config
20 | Subsystem powershell /usr/bin/pwsh -sshs -NoLogo -NoProfile
21 | sudo service sshd restart
22 |
23 | Enter-PSSession -HostName lnx-nug -UserName nuguser
24 | #>
--------------------------------------------------------------------------------
/Powershell/Powershell7/Data/csv.ps1:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DataKnox/CodeSamples/8b375eedfca5b9e5d8965cfedbb073dddcaac091/Powershell/Powershell7/Data/csv.ps1
--------------------------------------------------------------------------------
/Powershell/Powershell7/Data/excel.ps1:
--------------------------------------------------------------------------------
1 | If (!(Get-InstalledModule ImportExcel)) {
2 | Install-Module ImportExcel -Force
3 | }
4 | else {
5 | Write-Host "Module exists!"
6 | }
7 |
8 | #Import-Csv -Path '/home/knox/Downloads/star-wars/planets.csv' | Export-Excel -Path '/home/knox/Downloads/star-wars/planets.xlsx'
9 | Get-ChildItem -Path '/home/knox/Downloads/star-wars/' | ForEach-Object { if ($_.Extension -eq ".csv") { Export-Excel -path "/home/knox/Downloads/star-wars/$($_.BaseName).xlsx" } }
10 |
11 | Import-Excel -path '/home/knox/Downloads/star-wars/characters.xlsx'
12 |
13 | $chars = Import-Excel -path '/home/knox/Downloads/star-wars/characters.xlsx' | Select-Object name, species, homeworld
14 | #$chars | Export-Excel -path '/home/knox/Downloads/star-wars/output.xlsx'
15 |
16 | $planets = Import-Excel -path '/home/knox/Downloads/star-wars/planets.xlsx'
17 | foreach ($char in $chars) {
18 | foreach ($planet in $planets) {
19 | if ($char.homeworld -eq $planet.name) {
20 | $char | Add-Member -MemberType NoteProperty -name rotation -Value $planet.rotation_period -Force
21 | }
22 | }
23 | }
24 |
25 | $chars | Export-Excel -path '/home/knox/Downloads/star-wars/output.xlsx'
--------------------------------------------------------------------------------
/Powershell/Powershell7/Data/json.ps1:
--------------------------------------------------------------------------------
1 | Get-Content -Path './sw.json'
2 |
3 | $json = Get-Content -Path './sw.json'
4 |
5 | $json = $json | ConvertFrom-Json
6 | $json.movies
--------------------------------------------------------------------------------
/Powershell/Powershell7/Data/sql.ps1:
--------------------------------------------------------------------------------
1 | If (!(Get-InstalledModule SqlServer)) {
2 | Install-Module SqlServer -Force
3 | }
4 | else {
5 | Write-Host "Module exists!"
6 | }
7 |
8 | $query = @"
9 | SELECT
10 | *
11 | FROM
12 | dbo.people p
13 | JOIN
14 | dbo.planets pp
15 | ON p.HomePlanetID = pp.PlanetID
16 | "@
17 |
18 | Invoke-Sqlcmd -ServerInstance "localhost,1402" -Database "SWDB" -Query "SELECT * FROM dbo.People" -Username "SA" -Password "MyStrongPw!23"
19 |
20 | #Invoke-Sqlcmd -ServerInstance "localhost,1402" -Database "SWDB" -Query "SELECT * FROM dbo.People" -Username "SA" -Password "MyStrongPw!23" | Export-Excel -Path '/home/knox/Desktop/query.xlsx'
21 |
22 |
--------------------------------------------------------------------------------
/Powershell/Powershell7/Linux/help.ps1:
--------------------------------------------------------------------------------
1 | #Update the data files
2 | Update-Help -UICulture en-US -Force -ErrorAction SilentlyContinue
3 | #Get Help
4 | Get-Help Get-Process
--------------------------------------------------------------------------------
/Powershell/Powershell7/Linux/os.ps1:
--------------------------------------------------------------------------------
1 | Get-PSProvider
2 |
3 | Get-PSDrive
4 |
5 | #files and folders
6 | Get-Location
7 | Set-Location /home/knox/Downloads
8 | Get-ChildItem ./
9 |
10 | #Environment variables
11 | Get-ChildItem ENV:
12 |
13 | Get-Variable HOME
14 |
15 |
--------------------------------------------------------------------------------
/Powershell/Powershell7/Linux/services.ps1:
--------------------------------------------------------------------------------
1 | #Can you get the list of running daemons?
2 | Get-Service
3 | #Get running processes
4 | Get-Process
--------------------------------------------------------------------------------
/Powershell/Powershell7/Modules/install.ps1:
--------------------------------------------------------------------------------
1 | Get-PSRepository
2 |
3 | #Explore the module on the repo
4 | Find-Module -Name VMWare.PowerCLI
5 | #install
6 | If (!(Get-InstalledModule VMWare.PowerCLI)) {
7 | Install-Module VMWare.PowerCLI -Force
8 | }
9 |
10 | #note that the installed module is still not in the session
11 | Get-Module -ListAvailable | FT
12 |
13 | #Import the module into the session
14 | Import-Module VMWare.VimAutomation.Core
15 | # Get all commands for PowerCLI
16 | Get-Command -Module VMware.VimAutomation.Core
17 |
18 | Get-Help New-VM
--------------------------------------------------------------------------------
/Powershell/Powershell7/Modules/module.ps1:
--------------------------------------------------------------------------------
1 | Get-Module
2 |
3 | Get-Module -ListAvailable
4 |
5 | Get-Module -Name PSFtp -ListAvailable
6 |
7 | Get-InstalledModule
8 |
9 | Get-InstalledModule PSFtp
--------------------------------------------------------------------------------
/Powershell/Powershell7/Modules/uninstall.ps1:
--------------------------------------------------------------------------------
1 | Import-Module VMware.VimAutomation.Core
2 | Get-Module | FT
3 |
4 | #Remove-Module VMware.VimAutomation.Core
5 |
6 | Get-InstalledModule | Where-Object { $_.Name -like "VMWare*" } | Uninstall-Module
7 |
8 | Get-Module -ListAvailable | FT
--------------------------------------------------------------------------------
/Powershell/Powershell7/OS/cim.ps1:
--------------------------------------------------------------------------------
1 | #Get-cimclass
2 | Get-cimclass | Where-Object CimClassName -like "*network*"
3 |
4 | # Query a class
5 | Get-CimInstance -ClassName "CIM_NetworkAdapter"
6 |
7 | #Store a specific object in a variable
8 | $adapter = Get-CimInstance -ClassName "CIM_NetworkAdapter" | Where-Object Name -like "*Realtek*"
9 |
10 | $adapter
11 | # Get config info
12 | Get-CimInstance -ClassName "Win32_NetworkAdapterConfiguration"
13 |
14 | #Get OS info
15 | Get-CimInstance -ClassName Win32_OperatingSystem
16 | #Wait a minute, theres got to be more to our OS than that!
17 | Get-CimInstance -ClassName Win32_OperatingSystem | Get-Member
18 | Get-CimInstance -ClassName Win32_OperatingSystem | Select-Object *
19 | # Does it work with NICs too?
20 | Get-CimInstance -ClassName "Win32_NetworkAdapterConfiguration" | Select-Object *
21 | Get-CimInstance -ClassName "Win32_NetworkAdapterConfiguration" | Select-Object * | Where-Object { $_.DefaultIPGateway -ne $Null }
22 |
23 | #Common CIM classes
24 | <#
25 | Win32_Baseboard
26 | Win32_BIOS
27 | Win32_ComputerSystem
28 | Win32_LogicalDisk
29 | Win32_OperatingSystem
30 | Win32_PingStatus
31 | Win32_Printer
32 | Win32_PrinterShare
33 | Win32_PhysicalMemory
34 | Win32_Process
35 | Win32_Processor
36 | Win32_Share
37 | #>
--------------------------------------------------------------------------------
/Powershell/Powershell7/OS/env.ps1:
--------------------------------------------------------------------------------
1 | #Show all providers
2 | Get-PSProvider
3 | # Show powershell drives
4 | Get-PSDrive
5 | # Get all environment variables
6 | Get-ChildItem -path Env:
7 | # get current username env variable object
8 | $curr_username = Get-ChildItem -path Env: | Where-Object { $_.Name -eq "USERNAME" }
9 | # write to host
10 | Write-Host "$($curr_username.Name) : $($curr_username.Value)"
11 | # create a new env variable
12 | $env:mypassword = "My-Pw-Value"
13 |
14 | $pw = Get-ChildItem -path Env: | Where-Object { $_.Name -eq "mypassword" }
15 |
16 | Write-Host "$($pw.Name) : $($pw.Value)"
17 |
18 | # Create a psobject credential from env vars
19 | $PWord = ConvertTo-SecureString -String $pw.Value -AsPlainText -Force
20 | $Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $curr_username.Value, $PWord
21 | $Credential
--------------------------------------------------------------------------------
/Powershell/Powershell7/OS/nav.ps1:
--------------------------------------------------------------------------------
1 | Get-Location
2 |
3 | $loc = Get-Location
4 |
5 | $loc
6 |
7 | #change location
8 | $loc = Set-Location -path '/home/knox/Documents'
9 |
10 | $loc
11 |
12 | #alias
13 | sl -path '/home/knox/Downloads'
14 |
15 | Get-Location
16 |
17 | # Push current location to stack for tracking, then switch to home/knox
18 | Push-Location -path '/home/knox/'
19 |
20 | #verify we are in home/knox
21 | Get-Location
22 |
23 | #push current location to stack, then change to documents
24 | Push-Location -path '/home/knox/Documents'
25 |
26 | # verify
27 | Get-Location
28 |
29 | # jump back to last location
30 | Pop-Location
31 |
32 | Get-Location
33 |
34 |
35 |
--------------------------------------------------------------------------------
/Powershell/Powershell7/RealWorld/ftpauto.ps1:
--------------------------------------------------------------------------------
1 | # Install the module
2 | If (!(Get-InstalledModule PSFtp)) {
3 | Install-Module PSFtp -Force
4 | }
5 | else {
6 | Write-Host "Module exists!"
7 | }
8 |
9 | #set up login creds
10 | $user = "anonymous"
11 | $PWord = ConvertTo-SecureString -String "anonymous" -AsPlainText -Force
12 | $Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $user, $PWord
13 |
14 | #establish the connection and hold a session object
15 | Set-FtpConnection -Server "ftp://speedtest.tele2.net/" -Session MySesh -Credentials $Credential
16 | $sesh = Get-FtpConnection -Session MySesh
17 |
18 | # Download an item
19 | Get-FtpItem -Path "/512KB.zip" -Session $sesh
20 |
21 | #Check that todays folder exists
22 | If (!(Test-Path -Path "C:\FtpDownloads\512KB-$((Get-Date).toString('yyyy-MM-dd'))")) {
23 | New-Item -ItemType "directory" -Path "C:\FtpDownloads\512KB-$((Get-Date).toString('yyyy-MM-dd'))"
24 | }
25 |
26 | #Move file
27 | Move-Item -Path ".\512KB.zip" -Destination "C:\FtpDownloads\512KB-$((Get-Date).toString('yyyy-MM-dd'))"
--------------------------------------------------------------------------------
/Powershell/Powershell7/Web/api.ps1:
--------------------------------------------------------------------------------
1 | $baseUrl = "https://swapi.co/api/"
2 |
3 |
4 | # Set headers
5 | $headers = @{
6 | "Accept" = "application/json"
7 | }
8 |
9 | #See all available endpoints
10 | $response = Invoke-RestMethod -Uri $baseUrl -Method "GET" -Headers $headers -ContentType "application/json"
11 |
12 | #Set People endpoint
13 | $people = "people"
14 |
15 | $response = Invoke-RestMethod -Uri $baseUrl$people
16 |
17 | #$response
18 |
19 | #$response.results
20 | # Loop over each result and update Homeworld with another API call
21 | foreach ($person in $response.results) {
22 | $worldUrl = $person.homeworld
23 | $planetResponse = Invoke-RestMethod -Uri $worldUrl
24 | $person.homeworld = $planetResponse
25 | }
26 |
27 | $response.results
--------------------------------------------------------------------------------
/Powershell/Powershell7/Web/ftp.ps1:
--------------------------------------------------------------------------------
1 | # Install the module
2 | If (!(Get-InstalledModule PSFtp)) {
3 | Install-Module PSFtp -Force
4 | }
5 | else {
6 | Write-Host "Module exists!"
7 | }
8 |
9 | #set up login creds
10 | $user = "anonymous"
11 | $PWord = ConvertTo-SecureString -String "anonymous" -AsPlainText -Force
12 | $Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $user, $PWord
13 |
14 | #establish the connection and hold a session object
15 | Set-FtpConnection -Server "ftp://speedtest.tele2.net/" -Session MySesh -Credentials $Credential
16 | $sesh = Get-FtpConnection -Session MySesh
17 |
18 | # get all items
19 | Get-FtpChildItem -Session $sesh -Path /
20 | # Download an item
21 | Get-FtpItem -Path "/512KB.zip" -Session $sesh
22 | # Send an item
23 | Add-FtpItem -Path "/upload" -LocalPath '/home/knox/Documents/starwars.xlsx'
--------------------------------------------------------------------------------
/Powershell/Powershell7/Web/pokeapi.ps1:
--------------------------------------------------------------------------------
1 | $url = "https://pokeapi.co/api/v2/pokemon/"
2 |
3 | $response = Invoke-RestMethod -Uri $url -Method get -ResponseHeadersVariable r -StatusCodeVariable s
4 |
5 | if ($s -eq 200) {
6 | $response.results
7 | while ($response.next -ne $null) {
8 | $response = Invoke-RestMethod -uri $response.next
9 | $response.results
10 | }
11 | }
12 | else {
13 | $r
14 | }
--------------------------------------------------------------------------------
/Powershell/Powershell7/Web/postapi.ps1:
--------------------------------------------------------------------------------
1 | $url = 'https://postman-echo.com/post'
2 |
3 | $headers = @{
4 | "Accept" = "application/json"
5 | "Content-Type" = "application/json"
6 | }
7 |
8 | $payload = @{
9 | "firstName" = "Knox"
10 | "lastName" = "Hutchinson"
11 | "Description" = "Knoxs data demo"
12 | }
13 |
14 | $response = Invoke-RestMethod -Uri $url -Headers $headers -Method "Post" -Body ($payload | ConvertTo-Json) -ResponseHeadersVariable r -StatusCodeVariable s
15 |
16 | if ($s -ne 200) {
17 | Write-Host "failed"
18 | }
19 | else {
20 | Write-Host "Succeeded"
21 | $response
22 | $response.json
23 | }
--------------------------------------------------------------------------------
/Powershell/Powershell7/Web/webdownload.ps1:
--------------------------------------------------------------------------------
1 | $fileUrl = "http://speedtest.tele2.net/1MB.zip"
2 | $output = "./1MB.zip"
3 |
4 | Invoke-WebRequest -Uri $fileUrl -OutFile $output
--------------------------------------------------------------------------------
/Powershell/Powershell7/Web/webparse.ps1:
--------------------------------------------------------------------------------
1 | # Install the module
2 | If (!(Get-InstalledModule PowerHtml)) {
3 | Install-Module PowerHtml -Force
4 | }
5 | else {
6 | Write-Host "Module exists!"
7 | }
8 |
9 | #perform the web request
10 | $site = Invoke-WebRequest -Uri "https://www.newegg.com"
11 | # understand the properties
12 | $site | Get-Member
13 | #Dump it out to an html
14 | $site.Content | Out-File -FilePath '/home/knox/Desktop/newegg.html'
15 | #load the Html DOM
16 | $html = ConvertFrom-Html -Path '/home/knox/Desktop/newegg.html'
17 |
18 | $html.SelectNodes('//li')
19 |
20 |
21 | #Other useful members
22 | # $site.StatusCode
23 | # $site.InputFields
24 | # $site.Links
25 | # $site.Images
26 |
--------------------------------------------------------------------------------
/Python/AppDev/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM ubuntu:latest
2 |
3 | MAINTAINER Knox Hutchinson "khutchinson@cbtnuggets.com"
4 |
5 | RUN apt-get update -y && apt-get install -y python3-pip python3-dev
6 |
7 | CMD ["ufw allow 5000"]
8 |
9 | COPY ./requirements.txt /app/requirements.txt
10 |
11 | WORKDIR /app
12 |
13 | RUN pip3 install -r requirements.txt
14 |
15 | COPY ./app/ /app
16 |
17 | RUN chmod -R 777 /app
18 |
19 | ENTRYPOINT ["python3"]
20 |
21 | CMD ["myApi_ub.py"]
--------------------------------------------------------------------------------
/Python/AppDev/app/db.txt:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "hostname": "SW1",
4 | "ipaddr": "10.12.12.1"
5 | }
6 | ]
--------------------------------------------------------------------------------
/Python/AppDev/app/filename.log:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DataKnox/CodeSamples/8b375eedfca5b9e5d8965cfedbb073dddcaac091/Python/AppDev/app/filename.log
--------------------------------------------------------------------------------
/Python/AppDev/app/routerclass.py:
--------------------------------------------------------------------------------
1 | class Router:
2 | def __init__(self, hostname, ipadd):
3 | self.hostname = hostname
4 | self.ipadd = ipadd
5 |
--------------------------------------------------------------------------------
/Python/AppDev/docker-compose.yml:
--------------------------------------------------------------------------------
1 | version: '3.1'
2 | services:
3 | web:
4 | container_name: knoxapi
5 | build: .
6 | image: datanox/api:latest
7 | ports:
8 | - 5000:5000
9 | restart: always
--------------------------------------------------------------------------------
/Python/AppDev/init.sh:
--------------------------------------------------------------------------------
1 | docker build -t datanox/api:latest .
2 | docker-compose down
3 | docker-compose up -d
4 | sleep 10
5 | pytest --verbose ./tests/test_flask.py
6 | docker stop $(docker ps -a -q)
7 | docker rm $(docker ps -a -q)
--------------------------------------------------------------------------------
/Python/AppDev/requirements.txt:
--------------------------------------------------------------------------------
1 | Flask==1.1.2
--------------------------------------------------------------------------------
/Python/Azure/Functions/.funcignore:
--------------------------------------------------------------------------------
1 | .git*
2 | .vscode
3 | local.settings.json
4 | test
5 | .venv
--------------------------------------------------------------------------------
/Python/Azure/Functions/Meraki/__init__.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import json
3 | import azure.functions as func
4 |
5 |
6 | def main(req: func.HttpRequest, queueclient: func.Out[func.QueueMessage]) -> str:
7 | logging.info('Python HTTP trigger function processed a request.')
8 |
9 | try:
10 | req_body = req.get_json()
11 | except ValueError:
12 | pass
13 | else:
14 | sharedSecret = req_body.get('sharedSecret')
15 |
16 | if sharedSecret == 'foo':
17 | queueclient.set(json.dumps(req_body))
18 | return func.HttpResponse(body=json.dumps(req_body), status_code=200, headers={'Content-Type': 'application/json'})
19 | else:
20 | return func.HttpResponse(
21 | body="
Please pass a sharedSecret on the query string or in the request body
",
22 | status_code=400
23 | )
24 |
--------------------------------------------------------------------------------
/Python/Azure/Functions/Meraki/function.json:
--------------------------------------------------------------------------------
1 | {
2 | "scriptFile": "__init__.py",
3 | "bindings": [
4 | {
5 | "authLevel": "anonymous",
6 | "type": "httpTrigger",
7 | "direction": "in",
8 | "name": "req",
9 | "methods": [
10 | "get",
11 | "post"
12 | ]
13 | },
14 | {
15 | "type": "http",
16 | "direction": "out",
17 | "name": "$return"
18 | },
19 | {
20 | "type": "queue",
21 | "direction": "out",
22 | "name": "queueclient",
23 | "queueName": "merakiqueue",
24 | "connection": "AzureWebJobsStorage"
25 | }
26 | ]
27 | }
--------------------------------------------------------------------------------
/Python/Azure/Functions/Meraki/sample.dat:
--------------------------------------------------------------------------------
1 | {
2 | "name": "Azure"
3 | }
--------------------------------------------------------------------------------
/Python/Azure/Functions/host.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "2.0",
3 | "extensionBundle": {
4 | "id": "Microsoft.Azure.Functions.ExtensionBundle",
5 | "version": "[1.*, 2.0.0)"
6 | }
7 | }
--------------------------------------------------------------------------------
/Python/Azure/Functions/proxies.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "http://json.schemastore.org/proxies",
3 | "proxies": {}
4 | }
5 |
--------------------------------------------------------------------------------
/Python/Azure/Functions/requirements.txt:
--------------------------------------------------------------------------------
1 | azure-functions
--------------------------------------------------------------------------------
/Python/Azure/MerakiLocationScan/.funcignore:
--------------------------------------------------------------------------------
1 | .git*
2 | .vscode
3 | local.settings.json
4 | test
5 | .venv
--------------------------------------------------------------------------------
/Python/Azure/MerakiLocationScan/.vscode/extensions.json:
--------------------------------------------------------------------------------
1 | {
2 | "recommendations": [
3 | "ms-azuretools.vscode-azurefunctions",
4 | "ms-python.python"
5 | ]
6 | }
7 |
--------------------------------------------------------------------------------
/Python/Azure/MerakiLocationScan/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "0.2.0",
3 | "configurations": [
4 | {
5 | "name": "Attach to Python Functions",
6 | "type": "python",
7 | "request": "attach",
8 | "port": 9091,
9 | "preLaunchTask": "func: host start"
10 | }
11 | ]
12 | }
13 |
--------------------------------------------------------------------------------
/Python/Azure/MerakiLocationScan/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "azureFunctions.deploySubpath": ".",
3 | "azureFunctions.scmDoBuildDuringDeployment": true,
4 | "azureFunctions.pythonVenv": ".venv",
5 | "azureFunctions.projectLanguage": "Python",
6 | "azureFunctions.projectRuntime": "~3",
7 | "debug.internalConsoleOptions": "neverOpen",
8 | "python.pythonPath": ".venv/bin/python3"
9 | }
10 |
--------------------------------------------------------------------------------
/Python/Azure/MerakiLocationScan/.vscode/tasks.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "2.0.0",
3 | "tasks": [
4 | {
5 | "type": "func",
6 | "command": "host start",
7 | "problemMatcher": "$func-watch",
8 | "isBackground": true,
9 | "dependsOn": "pipInstall"
10 | },
11 | {
12 | "label": "pipInstall",
13 | "type": "shell",
14 | "osx": {
15 | "command": "${config:azureFunctions.pythonVenv}/bin/python -m pip install -r requirements.txt"
16 | },
17 | "windows": {
18 | "command": "${config:azureFunctions.pythonVenv}/Scripts/python -m pip install -r requirements.txt"
19 | },
20 | "linux": {
21 | "command": "${config:azureFunctions.pythonVenv}/bin/python -m pip install -r requirements.txt"
22 | },
23 | "problemMatcher": []
24 | }
25 | ]
26 | }
27 |
--------------------------------------------------------------------------------
/Python/Azure/MerakiLocationScan/MerakiLoc/__init__.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import json
3 | import azure.functions as func
4 |
5 |
6 | def main(req: func.HttpRequest, queueclient: func.Out[func.QueueMessage]) -> str:
7 | logging.info('Python HTTP trigger function processed a request.')
8 | print(req.method)
9 | if req.method == 'GET':
10 | queueclient.set('string')
11 | return func.HttpResponse(body='650a3212e0a8610f6e9eae1551f9e7e5727932d1', status_code=200)
12 | elif req.method == 'POST':
13 | try:
14 | req_body = req.get_json()
15 | except ValueError:
16 | pass
17 | else:
18 | sharedSecret = req_body.get('secret')
19 |
20 | if sharedSecret == 'foo':
21 | queueclient.set(json.dumps(req_body))
22 | return func.HttpResponse(body=json.dumps(req_body), status_code=201, headers={'Content-Type': 'application/json'})
23 | else:
24 | return func.HttpResponse(
25 | body="Please pass a sharedSecret on the query string or in the request body
",
26 | status_code=401
27 | )
28 |
--------------------------------------------------------------------------------
/Python/Azure/MerakiLocationScan/MerakiLoc/function.json:
--------------------------------------------------------------------------------
1 | {
2 | "scriptFile": "__init__.py",
3 | "bindings": [
4 | {
5 | "authLevel": "anonymous",
6 | "type": "httpTrigger",
7 | "direction": "in",
8 | "name": "req",
9 | "methods": [
10 | "get",
11 | "post"
12 | ]
13 | },
14 | {
15 | "type": "http",
16 | "direction": "out",
17 | "name": "$return"
18 | },
19 | {
20 | "type": "queue",
21 | "direction": "out",
22 | "name": "queueclient",
23 | "queueName": "merakiqueue",
24 | "connection": "AzureWebJobsStorage"
25 | }
26 | ]
27 | }
--------------------------------------------------------------------------------
/Python/Azure/MerakiLocationScan/MerakiLoc/sample.dat:
--------------------------------------------------------------------------------
1 | {
2 | "name": "Azure"
3 | }
--------------------------------------------------------------------------------
/Python/Azure/MerakiLocationScan/host.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "2.0",
3 | "extensionBundle": {
4 | "id": "Microsoft.Azure.Functions.ExtensionBundle",
5 | "version": "[1.*, 2.0.0)"
6 | }
7 | }
--------------------------------------------------------------------------------
/Python/Azure/MerakiLocationScan/proxies.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "http://json.schemastore.org/proxies",
3 | "proxies": {}
4 | }
5 |
--------------------------------------------------------------------------------
/Python/Azure/MerakiLocationScan/requirements.txt:
--------------------------------------------------------------------------------
1 | azure-functions
--------------------------------------------------------------------------------
/Python/Data/azkvdemo.py:
--------------------------------------------------------------------------------
1 | import os
2 | from dotenv import load_dotenv
3 | from azure.keyvault.secrets import SecretClient
4 | from azure.identity import DefaultAzureCredential
5 |
6 | load_dotenv()
7 |
8 | key_vault = os.environ.get('KEY_VAULT_NAME')
9 | kv_url = f"https://{key_vault}.vault.azure.net"
10 |
11 | credential = DefaultAzureCredential()
12 | client = SecretClient(vault_url=kv_url, credential=credential)
13 |
14 | secretName = input("Input a name for your secret > ")
15 | secretValue = input("Input a value for your secret > ")
16 |
17 | client.set_secret(secretName, secretValue)
18 |
19 | secret = client.get_secret(secretName)
20 |
21 | print(f"The secret is {secret.value}")
22 |
--------------------------------------------------------------------------------
/Python/Data/demo.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Welcome to Knox Data
6 |
7 |
8 |
9 | Am I encrypted?
10 |
11 |
12 |
--------------------------------------------------------------------------------
/Python/Data/security.py:
--------------------------------------------------------------------------------
1 | from dotenv import load_dotenv
2 | import os
3 |
4 |
5 | load_dotenv()
6 |
7 | username = os.environ.get('USERNAME_NET')
8 | password = os.environ.get('PASSWORD')
9 |
10 | print(username)
11 | print(password)
12 |
--------------------------------------------------------------------------------
/Python/Data/sql.py:
--------------------------------------------------------------------------------
1 | import pyodbc
2 |
3 | conn = pyodbc.connect(
4 | 'DRIVER={ODBC Driver 17 for SQL Server};SERVER=localhost,1401;DATABASE=WideWorldImporters;UID=sa;PWD=MyStrongPw!23')
5 |
6 | cursor = conn.cursor()
7 |
8 | cursor.execute(
9 | "select PurchaseOrderId, SupplierId from Purchasing.PurchaseOrders")
10 |
11 | rows = cursor.fetchall()
12 | # print(rows)
13 | for row in rows:
14 | print(row.PurchaseOrderId, row.SupplierId)
15 |
--------------------------------------------------------------------------------
/Python/Data/starwars.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 | base_url = 'https://swapi.co/api/'
5 | endpoint = 'people/2/'
6 | headers = {'Accept': 'application/json'}
7 |
8 | response = requests.get(url=f"{base_url}{endpoint}", headers=headers)
9 |
10 | if response.status_code == 200:
11 | data = response.json()
12 | print(f"Name: {data['name']}")
13 | print(f"Height {data['height']}")
14 | print(
15 | f"Homeworld: {requests.get(data['homeworld'],headers=headers).json()['name']}")
16 |
--------------------------------------------------------------------------------
/Python/Data/starwars.xlsx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DataKnox/CodeSamples/8b375eedfca5b9e5d8965cfedbb073dddcaac091/Python/Data/starwars.xlsx
--------------------------------------------------------------------------------
/Python/Data/swexcel.py:
--------------------------------------------------------------------------------
1 | import openpyxl
2 |
3 | wb = openpyxl.load_workbook('/home/knox/Documents/starwars.xlsx')
4 | ws = wb.active
5 |
6 | row_count = ws.max_row+1
7 |
8 | characters = []
9 |
10 | for x in range(2, row_count):
11 | character = {}
12 | character['first_name'] = ws.cell(row=x, column=1).value
13 | character['last_name'] = ws.cell(row=x, column=2).value
14 | character['homeplant'] = ws.cell(row=x, column=3).value
15 | characters.append(character)
16 |
17 | for char in characters:
18 | print(char)
19 |
--------------------------------------------------------------------------------
/Python/Docker/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM ubuntu:18.04
2 |
3 | MAINTAINER Knox Hutchinson "khutchinson@cbtnuggets.com"
4 |
5 | RUN apt-get update -y && apt-get install -y python3-pip python3-dev
6 |
7 | CMD ["ufw allow 5000"]
8 |
9 | COPY ./requirements.txt /app/requirements.txt
10 |
11 | WORKDIR /app
12 |
13 | RUN pip3 install -r requirements.txt
14 |
15 | COPY ./myAPI/myAPI.py /app
16 |
17 | ENTRYPOINT ["python3"]
18 |
19 | CMD ["myAPI.py"]
--------------------------------------------------------------------------------
/Python/Docker/build.sh:
--------------------------------------------------------------------------------
1 | sudo docker build -t dockerfile:latest .
2 |
3 | sudo docker run -d -p 5000:5000 dockerfile
4 |
5 | sudo docker logs instancieidhere
6 |
7 | sudo docker ps
8 |
9 | sudo docker stop instancieidhere
10 |
--------------------------------------------------------------------------------
/Python/Docker/install.sh:
--------------------------------------------------------------------------------
1 | sudo apt-get remove docker docker-engine docker.io containerd runc
2 |
3 | sudo apt-get update
4 |
5 | sudo apt-get install \
6 | apt-transport-https \
7 | ca-certificates \
8 | curl \
9 | gnupg-agent \
10 | software-properties-common
11 |
12 | curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
13 |
14 | # use the following to verify the add succeeded
15 | # sudo apt-key fingerprint 0EBFCD88
16 |
17 | sudo add-apt-repository \
18 | "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
19 | $(lsb_release -cs) \
20 | stable"
21 |
22 | sudo apt-get update
23 |
24 | sudo apt-get install docker-ce docker-ce-cli containerd.io
25 |
26 | # https://hub.docker.com/r/06kellyjac/nyancat/
27 | sudo docker run -it --rm --name nyancat 06kellyjac/nyancat
--------------------------------------------------------------------------------
/Python/Docker/myAPI/myAPI.py:
--------------------------------------------------------------------------------
1 | from flask import Flask, jsonify
2 |
3 | app = Flask(__name__)
4 |
5 |
6 | @app.route('/api/endpoint', methods=['GET'])
7 | def get_data():
8 | return (jsonify({'message': 'received'}), 200)
9 |
10 |
11 | if __name__ == '__main__':
12 | app.run(host='0.0.0.0')
13 |
--------------------------------------------------------------------------------
/Python/Docker/requirements.txt:
--------------------------------------------------------------------------------
1 | Flask==1.1.1
--------------------------------------------------------------------------------
/Python/Docker/sqlcont.sh:
--------------------------------------------------------------------------------
1 | sudo docker pull mcr.microsoft.com/mssql/server:2019-CU8-ubuntu-16.04
2 |
3 | sudo docker run -e 'ACCEPT_EULA=Y' -e 'MSSQL_SA_PASSWORD=MyStrongPw!23' \
4 | --name 'sql1' -p 1401:1433 \
5 | -v sql1data:/var/opt/mssql \
6 | -d mcr.microsoft.com/mssql/server:2019-CU8-ubuntu-16.04
7 |
8 | sudo docker exec -it sql1 mkdir /var/opt/mssql/backup
9 |
10 | cd ~
11 | curl -L -o wwi.bak 'https://github.com/Microsoft/sql-server-samples/releases/download/wide-world-importers-v1.0/WideWorldImporters-Full.bak'
12 |
13 | sudo docker cp wwi.bak sql1:/var/opt/mssql/backup
14 |
15 | sudo docker exec -it sql1 /opt/mssql-tools/bin/sqlcmd -S localhost \
16 | -U SA -P 'MyStrongPw!23' \
17 | -Q 'RESTORE FILELISTONLY FROM DISK = "/var/opt/mssql/backup/wwi.bak"' \
18 | | tr -s ' ' | cut -d ' ' -f 1-2
19 |
20 | sudo docker exec -it sql1 /opt/mssql-tools/bin/sqlcmd \
21 | -S localhost -U SA -P 'MyStrongPw!23' \
22 | -Q 'RESTORE DATABASE WideWorldImporters FROM DISK = "/var/opt/mssql/backup/wwi.bak" WITH MOVE "WWI_Primary" TO "/var/opt/mssql/data/WideWorldImporters.mdf", MOVE "WWI_UserData" TO "/var/opt/mssql/data/WideWorldImporters_userdata.ndf", MOVE "WWI_Log" TO "/var/opt/mssql/data/WideWorldImporters.ldf", MOVE "WWI_InMemory_Data_1" TO "/var/opt/mssql/data/WideWorldImporters_InMemory_Data_1"'
--------------------------------------------------------------------------------
/Python/Docker/swdocker.sh:
--------------------------------------------------------------------------------
1 | sudo docker pull mcr.microsoft.com/mssql/server:2019-GA-ubuntu-16.04
2 |
3 | sudo docker run -e 'ACCEPT_EULA=Y' -e 'MSSQL_SA_PASSWORD=MyStrongPw!23' \
4 | --name 'swsql' -p 1402:1433 \
5 | -v sql1data:/var/opt/mssql \
6 | -d mcr.microsoft.com/mssql/server:2019-GA-ubuntu-16.04
7 |
8 | sudo docker exec -it swsql mkdir /var/opt/mssql/backup
9 |
10 | cd ~
11 |
12 | sudo docker cp SWDB.bak swsql:/var/opt/mssql/backup
13 |
14 | sudo docker exec -it swsql /opt/mssql-tools/bin/sqlcmd -S localhost \
15 | -U SA -P 'MyStrongPw!23' \
16 | -Q 'RESTORE FILELISTONLY FROM DISK = "/var/opt/mssql/backup/SWDB.bak"' \
17 | | tr -s ' ' | cut -d ' ' -f 1-2
18 |
19 | sudo docker exec -it swsql /opt/mssql-tools/bin/sqlcmd \
20 | -S localhost -U SA -P 'MyStrongPw!23' \
21 | -Q 'RESTORE DATABASE SWDB FROM DISK = "/var/opt/mssql/backup/SWDB.bak" WITH MOVE "SWDB" TO "/var/opt/mssql/data/SWDB.mdf", MOVE "SWDB_Log" TO "/var/opt/mssql/data/SWDB_log.ldf"'
--------------------------------------------------------------------------------
/Python/Networking/Collaboration/cleanup.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 | token = 'MjgyYzQyYjEtNTNmOS00NTQ0LWEyNjMtZDA5OWU2NjIxYjFkZjdiOGJjMzMtNjQ4_PF84_75e84279-5cba-4094-949a-7133a3be6509'
5 |
6 | ### DELETE ROOM ###
7 | room_url = 'https://api.ciscospark.com/v1/rooms'
8 | headers = {'Authorization': f'Bearer {token}',
9 | 'Content-Type': 'application/json'}
10 |
11 |
12 | get_rooms = requests.get(room_url, headers=headers).json()
13 |
14 | rooms = get_rooms['items']
15 | for room in rooms:
16 | if room['title'] == 'CBT Room':
17 | roomId = room['id']
18 | del_room_url = f'{room_url}/{roomId}'
19 | del_room = requests.delete(del_room_url, headers=headers)
20 |
21 |
22 | ####### DELETE TEAM ##############
23 | url = 'https://api.ciscospark.com/v1/teams'
24 |
25 | get_response = requests.get(url, headers=headers).json()
26 |
27 | teams = get_response['items']
28 | for team in teams:
29 | if team['name'] == 'CBT Team':
30 | teamId = team['id']
31 | del_team_url = f'{url}/{teamId}'
32 | del_team = requests.delete(del_team_url, headers=headers)
33 |
--------------------------------------------------------------------------------
/Python/Networking/Collaboration/uds Get Users.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import xml.dom.minidom
3 | import xmltodict
4 | import urllib3
5 | urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
6 | #### For use with the DevNet Sandbox CUCM 11.5 #####
7 | url = 'https://10.10.20.1/cucm-uds'
8 | endpoint = 'users'
9 |
10 | users_url = f'{url}/{endpoint}'
11 |
12 | headers = {
13 | 'Accept': 'application/xml',
14 | 'Content-Type': 'application/xml'
15 | }
16 |
17 | username = 'administrator'
18 | pw = 'ciscopsdt'
19 |
20 | r = requests.get(users_url, auth=(username, pw), verify=False)
21 |
22 | # Pretty up the XML response
23 | tree = xml.dom.minidom.parseString(r.text)
24 | pretty = tree.toprettyxml()
25 |
26 | # Convert to Python Dict
27 | xmldata = xmltodict.parse(pretty)
28 | #print(json.dumps(xmldata, indent=2, sort_keys=True))
29 | users = xmldata['users']['user']
30 | for user in users:
31 | print(f"{user['lastName']} {user['firstName']}")
32 | print(f"ID: {user['id']}")
33 | print(" ")
34 |
--------------------------------------------------------------------------------
/Python/Networking/DNA/DNACauth.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 | base_url = "https://192.168.10.214/dna"
5 | auth_endpoint = "/system/api/v1/auth/token"
6 |
7 | username = 'admin'
8 | password = 'dnacenter!@#99'
9 |
10 | auth_headers = {
11 | "Content-Type": "application/json",
12 | "Accept": "application/json"
13 | }
14 |
15 | auth_response = requests.post(url=f"{base_url}{auth_endpoint}", auth=(
16 | username, password), headers=auth_headers, verify=False).json()
17 |
18 | #print(json.dumps(auth_response, indent=2))
19 |
20 | token = auth_response['Token']
21 |
22 | req_headers = {
23 | "Content-Type": "application/json",
24 | "Accept": "application/json",
25 | "x-auth-token": token
26 | }
27 |
--------------------------------------------------------------------------------
/Python/Networking/DNA/DNACcreatesite.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 | base_url = "https://192.168.10.214/dna"
5 | auth_endpoint = "/system/api/v1/auth/token"
6 |
7 | username = 'admin'
8 | password = 'dnacenter!@#99'
9 |
10 | auth_headers = {
11 | "Content-Type": "application/json",
12 | "Accept": "application/json"
13 | }
14 |
15 | auth_response = requests.post(url=f"{base_url}{auth_endpoint}", auth=(
16 | username, password), headers=auth_headers, verify=False).json()
17 |
18 | #print(json.dumps(auth_response, indent=2))
19 |
20 | token = auth_response['Token']
21 |
22 | req_headers = {
23 | "Content-Type": "application/json",
24 | "Accept": "application/json",
25 | "x-auth-token": token
26 | }
27 |
28 | site_endpoint = '/intent/api/v1/site'
29 |
30 | payload = {
31 | "type": "area",
32 | "site": {
33 | "area": {
34 | "name": "Illinois",
35 | "parentName": "Global"
36 | }
37 | }
38 | }
39 |
40 | site_response = requests.post(url=f"{base_url}{site_endpoint}",
41 | headers=req_headers, data=json.dumps(payload), verify=False).json()
42 | print(json.dumps(site_response, indent=2))
43 |
--------------------------------------------------------------------------------
/Python/Networking/DNA/DNACdevices.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 | base_url = "https://192.168.10.214/dna"
5 | auth_endpoint = "/system/api/v1/auth/token"
6 |
7 | username = 'admin'
8 | password = 'dnacenter!@#99'
9 |
10 | auth_headers = {
11 | "Content-Type": "application/json",
12 | "Accept": "application/json"
13 | }
14 |
15 | auth_response = requests.post(url=f"{base_url}{auth_endpoint}", auth=(
16 | username, password), headers=auth_headers, verify=False).json()
17 |
18 | #print(json.dumps(auth_response, indent=2))
19 |
20 | token = auth_response['Token']
21 |
22 | req_headers = {
23 | "Content-Type": "application/json",
24 | "Accept": "application/json",
25 | "x-auth-token": token
26 | }
27 |
28 | device_endpoint = "/intent/api/v1/network-device"
29 |
30 | devices = requests.get(url=f"{base_url}{device_endpoint}",
31 | headers=req_headers, verify=False).json()['response']
32 |
33 | #print(json.dumps(devices, indent=2))
34 | for device in devices:
35 | if device['hostname'] == "NOLA-EDGE2.nuggetlab.local":
36 | dev_id = device['id']
37 | dev_vlan_endpoint = f"/intent/api/v1/network-device/{dev_id}/vlan"
38 |
39 | dev_vlans = requests.get(url=f"{base_url}{dev_vlan_endpoint}",
40 | headers=req_headers, verify=False).json()['response']
41 |
42 | print(json.dumps(dev_vlans, indent=2))
43 |
--------------------------------------------------------------------------------
/Python/Networking/DNA/DNACgetsites.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 | base_url = "https://192.168.10.214/dna"
5 | auth_endpoint = "/system/api/v1/auth/token"
6 |
7 | username = 'admin'
8 | password = 'dnacenter!@#99'
9 |
10 | auth_headers = {
11 | "Content-Type": "application/json",
12 | "Accept": "application/json"
13 | }
14 |
15 | auth_response = requests.post(url=f"{base_url}{auth_endpoint}", auth=(
16 | username, password), headers=auth_headers, verify=False).json()
17 |
18 | #print(json.dumps(auth_response, indent=2))
19 |
20 | token = auth_response['Token']
21 |
22 | req_headers = {
23 | "Content-Type": "application/json",
24 | "Accept": "application/json",
25 | "x-auth-token": token
26 | }
27 |
28 | sites_endpoint = "/intent/api/v1/topology/site-topology"
29 |
30 | sites = requests.get(url=f"{base_url}{sites_endpoint}",
31 | headers=req_headers, verify=False).json()['response']
32 |
33 | print(json.dumps(sites, indent=2))
34 |
--------------------------------------------------------------------------------
/Python/Networking/DNA/DNACsdadev.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 | base_url = "https://192.168.10.214/dna"
5 | auth_endpoint = "/system/api/v1/auth/token"
6 |
7 | username = 'admin'
8 | password = 'dnacenter!@#99'
9 |
10 | auth_headers = {
11 | "Content-Type": "application/json",
12 | "Accept": "application/json"
13 | }
14 |
15 | auth_response = requests.post(url=f"{base_url}{auth_endpoint}", auth=(
16 | username, password), headers=auth_headers, verify=False).json()
17 |
18 | #print(json.dumps(auth_response, indent=2))
19 |
20 | token = auth_response['Token']
21 |
22 | req_headers = {
23 | "Content-Type": "application/json",
24 | "Accept": "application/json",
25 | "x-auth-token": token
26 | }
27 |
28 | device_endpoint = "/intent/api/v1/network-device"
29 |
30 | devices = requests.get(url=f"{base_url}{device_endpoint}",
31 | headers=req_headers, verify=False).json()['response']
32 |
33 | #print(json.dumps(devices, indent=2))
34 | for device in devices:
35 | if device['hostname'] == "NOLA-EDGE2.nuggetlab.local":
36 | dev_ip = device['managementIpAddress']
37 |
38 | sda_endpoint = f"/intent/api/v1/business/sda/device?deviceIPAddress={dev_ip}"
39 |
40 | response = requests.get(
41 | url=f"{base_url}{sda_endpoint}", headers=req_headers, verify=False).json()
42 |
43 | print(json.dumps(response, indent=2))
44 |
--------------------------------------------------------------------------------
/Python/Networking/DNA/ENAUTOauthentication.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 | base_url = "https://dcloud-dna-center-inst-rtp.cisco.com/dna/"
5 | auth_endpoint = "system/api/v1/auth/token"
6 |
7 | user = 'demo'
8 | password = 'demo1234!'
9 |
10 | auth_response = requests.post(
11 | url=f"{base_url}{auth_endpoint}", auth=(user, password)).json()
12 |
13 | token = auth_response['Token']
14 |
15 | headers = {
16 | "Accept": "application/json",
17 | "Content-Type": "application/json",
18 | "x-auth-token": token
19 | }
20 |
--------------------------------------------------------------------------------
/Python/Networking/DNA/ENAUTOcommandrunner.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 | ################ LOGIN ######################
5 | base_url = "https://sandboxdnac2.cisco.com/dna/"
6 | auth_endpoint = "system/api/v1/auth/token"
7 | user = 'devnetuser'
8 | pw = 'Cisco123!'
9 |
10 | response = requests.post(
11 | url=f"{base_url}{auth_endpoint}", auth=(user, pw)).json()
12 | # print(response)
13 | token = response['Token']
14 |
15 | headers = {
16 | 'x-auth-token': token,
17 | 'Accept': "application/json",
18 | 'Content-Type': 'application/json'
19 | }
20 |
21 | device_url = "intent/api/v1/network-device?family=Switches and Hubs&type=Cisco Catalyst 9300 Switch"
22 |
23 | devices_response = requests.get(
24 | url=f"{base_url}{device_url}", headers=headers, verify=False).json()
25 |
26 | print(json.dumps(devices_response, indent=2))
27 |
28 | device_Ids = []
29 | for device in devices_response['response']:
30 | device_id = device['id']
31 | device_Ids.append(device_id)
32 |
33 | # print(device_Ids)
34 |
35 | payload = {
36 | "commands": [
37 | "show version"
38 | ],
39 | "deviceUuids": device_Ids
40 | }
41 |
42 | command_endpoint = "intent/api/v1/network-device-poller/cli/read-request"
43 |
44 | cli_response = requests.post(
45 | url=f"{base_url}{command_endpoint}", headers=headers, data=json.dumps(payload), verify=False).json()
46 |
47 | print(json.dumps(cli_response, indent=2))
48 |
--------------------------------------------------------------------------------
/Python/Networking/DNA/ENAUTOdna.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 | ################ LOGIN ######################
5 | url = "https://dcloud-dna-center-inst-rtp.cisco.com/dna/system/api/v1/auth/token"
6 |
7 | user = 'demo'
8 | pw = 'demo1234!'
9 |
10 | response = requests.post(url, auth=(user, pw)).json()
11 |
12 | print(response)
13 | token = response['Token']
14 |
15 | url = "https://dcloud-dna-center-inst-rtp.cisco.com/dna/intent/api/v1/site"
16 |
17 | payload = {}
18 | headers = {
19 | 'x-auth-token': token,
20 | 'Accept': 'application/json'
21 | }
22 |
23 | response = requests.get(url, headers=headers).json()
24 |
25 | print(json.dumps(response, indent=2))
26 |
--------------------------------------------------------------------------------
/Python/Networking/DNA/ENAUTOgetinventory.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 | ################ LOGIN ######################
5 | base_url = "https://sandboxdnac2.cisco.com/dna/"
6 | auth_endpoint = "system/api/v1/auth/token"
7 | user = 'devnetuser'
8 | pw = 'Cisco123!'
9 |
10 | response = requests.post(
11 | url=f"{base_url}{auth_endpoint}", auth=(user, pw)).json()
12 | # print(response)
13 | token = response['Token']
14 |
15 | headers = {
16 | 'x-auth-token': token,
17 | 'Accept': 'application/json'
18 | }
19 |
20 | device_endpoint = "intent/api/v1/network-device"
21 |
22 | dev_response = requests.get(
23 | url=f"{base_url}{device_endpoint}", headers=headers).json()
24 | print(json.dumps(dev_response, indent=2))
25 |
--------------------------------------------------------------------------------
/Python/Networking/DNA/ENAUTOgetsites.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 | base_url = "https://dcloud-dna-center-inst-rtp.cisco.com/dna/"
5 | auth_endpoint = "system/api/v1/auth/token"
6 |
7 | user = 'demo'
8 | password = 'demo1234!'
9 |
10 | auth_response = requests.post(
11 | url=f"{base_url}{auth_endpoint}", auth=(user, password)).json()
12 |
13 | token = auth_response['Token']
14 |
15 | headers = {
16 | "Accept": "application/json",
17 | "Content-Type": "application/json",
18 | "x-auth-token": token
19 | }
20 |
21 | # site_endpoint = 'intent/api/v1/site'
22 |
23 | # site_response = requests.get(
24 | # url=f"{base_url}{site_endpoint}", headers=headers).json()
25 | # print(json.dumps(site_response, indent=2))
26 |
27 | topology_endpoint = "intent/api/v1/topology/site-topology"
28 | site_response = requests.get(
29 | url=f"{base_url}{topology_endpoint}", headers=headers).json()
30 | print(json.dumps(site_response, indent=2))
31 |
--------------------------------------------------------------------------------
/Python/Networking/DNA/auth.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 | base_url = "https://dcloud-dna-center-inst-rtp.cisco.com/dna/"
5 | auth_endpoint = "system/api/v1/auth/token"
6 |
7 | user = 'demo'
8 | password = 'demo1234!'
9 |
10 | auth_response = requests.post(
11 | url=f"{base_url}{auth_endpoint}", auth=(user, password)).json()
12 |
13 | token = auth_response['Token']
14 |
15 | headers = {
16 | "x-auth-token": token,
17 | "Accept": "application/json",
18 | "Content-Type": "application/json"
19 | }
20 |
21 | print(token)
22 |
--------------------------------------------------------------------------------
/Python/Networking/DNA/createsite.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 | ################ LOGIN ######################
5 | url = "https://sandboxdnac2.cisco.com/dna/system/api/v1/auth/token"
6 |
7 | user = 'devnetuser'
8 | pw = 'Cisco123!'
9 |
10 | response = requests.post(url, auth=(user, pw)).json()
11 | # print(response)
12 | token = response['Token']
13 |
14 | url = "https://sandboxdnac2.cisco.com/dna/intent/api/v1/site"
15 |
16 | payload = {}
17 | headers = {
18 | 'x-auth-token': token,
19 | 'Accept': 'application/json'
20 | }
21 |
22 | my_site = {
23 | "type": "area",
24 | "site": {
25 | "area": {
26 | "name": "Baton Rouge",
27 | "parentName": "Global/USA"
28 | }
29 | }
30 | }
31 |
32 | response = requests.post(url, data=my_site, headers=headers).json()
33 |
34 | print(json.dumps(response, indent=2))
35 |
--------------------------------------------------------------------------------
/Python/Networking/DNA/getsite.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 | ################ LOGIN ######################
5 | url = "https://sandboxdnac2.cisco.com/dna/system/api/v1/auth/token"
6 |
7 | user = 'devnetuser'
8 | pw = 'Cisco123!'
9 |
10 | response = requests.post(url, auth=(user, pw)).json()
11 | # print(response)
12 | token = response['Token']
13 |
14 | url = "https://sandboxdnac2.cisco.com/dna/intent/api/v1/site"
15 |
16 | payload = {}
17 | headers = {
18 | 'x-auth-token': token,
19 | 'Accept': 'application/json'
20 | }
21 |
22 | response = requests.get(url, headers=headers).json()
23 |
24 | print(json.dumps(response, indent=2))
25 |
--------------------------------------------------------------------------------
/Python/Networking/DNA/getsitetop.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 | ################ LOGIN ######################
5 | url = "https://sandboxdnac2.cisco.com/dna/system/api/v1/auth/token"
6 |
7 | user = 'devnetuser'
8 | pw = 'Cisco123!'
9 |
10 | response = requests.post(url, auth=(user, pw)).json()
11 | # print(response)
12 | token = response['Token']
13 |
14 | url = "https://sandboxdnac2.cisco.com/dna/intent/api/v1/topology/site-topology"
15 |
16 | payload = {}
17 | headers = {
18 | 'x-auth-token': token,
19 | 'Accept': 'application/json'
20 | }
21 |
22 | response = requests.get(url, headers=headers).json()
23 |
24 | print(json.dumps(response, indent=2))
25 |
--------------------------------------------------------------------------------
/Python/Networking/IOS-XE/EANUTOrestconfcapabilities.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 | router = {
5 | "host": "ios-xe-mgmt.cisco.com",
6 | "port": "9443",
7 | "user": "root",
8 | "password": "D_Vay!_10&"
9 | }
10 |
11 | url = f"https://{router['host']}:{router['port']}/restconf/data/netconf-state/capabilities"
12 |
13 | headers = {
14 | "Accept": "application/yang-data+json",
15 | "Content-Type": "application/yang-data+json"
16 | }
17 |
18 | response = requests.get(url=url, headers=headers, auth=(
19 | router['user'], router['password']), verify=False)
20 |
21 | if response.status_code == 200:
22 | response_dict = response.json()
23 | for capability in response_dict['ietf-netconf-monitoring:capabilities']['capability']:
24 | print(capability)
25 |
--------------------------------------------------------------------------------
/Python/Networking/IOS-XE/ENAUTOcapabilities.py:
--------------------------------------------------------------------------------
1 | from ncclient import manager
2 | import logging
3 |
4 | logging.basicConfig(level=logging.DEBUG)
5 |
6 | router = {
7 | "host": "ios-xe-mgmt-latest.cisco.com",
8 | "port": "10000",
9 | "username": "developer",
10 | "password": "C1sco12345"
11 | }
12 |
13 | with manager.connect(**router, hostkey_verify=False) as m:
14 | print('hello world')
15 |
--------------------------------------------------------------------------------
/Python/Networking/IOS-XE/ENAUTOedit.py:
--------------------------------------------------------------------------------
1 | from ncclient import manager
2 | from router_info import router
3 |
4 | config_template = open(
5 | "E:/dev/CodeSamples/Python/Networking/IOS-XE/ios_config.xml").read()
6 |
7 | netconf_config = config_template.format(
8 | interface_name="GigabitEthernet2", interface_desc="CBT Nuggets wuz here")
9 |
10 | with manager.connect(**router, hostkey_verify=False) as m:
11 | response = m.edit_config(netconf_config, target="candidate")
12 |
13 | print(response)
14 |
--------------------------------------------------------------------------------
/Python/Networking/IOS-XE/ENAUTOget.py:
--------------------------------------------------------------------------------
1 | from ncclient import manager
2 | #import logging
3 | import xmltodict
4 |
5 | # logging.basicConfig(level=logging.DEBUG)
6 |
7 | router = {
8 | "host": "ios-xe-mgmt-latest.cisco.com",
9 | "port": "10000",
10 | "username": "developer",
11 | "password": "C1sco12345"
12 | }
13 |
14 | int_filter = """
15 |
16 |
17 |
18 | GigabitEthernet2
19 |
20 |
21 |
22 |
23 | GigabitEthernet2
24 |
25 |
26 |
27 | """
28 |
29 | with manager.connect(**router, hostkey_verify=False) as m:
30 | netconf_response = m.get(int_filter)
31 |
32 | python_response = xmltodict.parse(netconf_response.xml)["rpc-reply"]["data"]
33 | op = python_response["interfaces-state"]["interface"]
34 | config = python_response["interfaces"]["interface"]
35 |
36 | print(f"Name: {config['name']['#text']}")
37 | print(f"Packets In: {op['statistics']['in-unicast-pkts']}")
38 |
--------------------------------------------------------------------------------
/Python/Networking/IOS-XE/ENAUTOnetmiko.py:
--------------------------------------------------------------------------------
1 | from netmiko import ConnectHandler
2 | from dotenv import load_dotenv
3 | load_dotenv()
4 | router = {
5 | "host": "ios-xe-mgmt-latest.cisco.com",
6 | "port": 8181,
7 | "username": "root",
8 | "password": "D_Vay!_10&",
9 | "device_type": "cisco_ios"
10 | }
11 |
12 | configs = ['int loopback101', 'ip address 10.99.98.1 255.255.255.0', 'no shut']
13 |
14 | try:
15 | c = ConnectHandler(**router)
16 | c.enable()
17 | c.send_config_set(configs)
18 | response = c.send_command("show ip int brief", use_textfsm=True)
19 | c.disconnect()
20 | except Exception as ex:
21 | print(ex)
22 | else:
23 | print(response)
24 |
--------------------------------------------------------------------------------
/Python/Networking/IOS-XE/ENAUTOrestconfGET.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 | router = {
5 | "host": "ios-xe-mgmt.cisco.com",
6 | "port": "9443",
7 | "user": "root",
8 | "password": "D_Vay!_10&"
9 | }
10 |
11 | headers = {
12 | "Accept": "application/yang-data+json",
13 | "Content-Type": "application/yang-data+json"
14 | }
15 |
16 | # url = f"https://{router['host']}:{router['port']}/restconf/data/ietf-routing:routing"
17 |
18 | # response = requests.get(url=url, headers=headers, auth=(
19 | # router['user'], router['password']), verify=False).json()
20 |
21 | # print(json.dumps(response, indent=2))
22 |
23 | url = f"https://{router['host']}:{router['port']}/restconf/data/Cisco-IOS-XE-interfaces-oper:interfaces/"
24 |
25 | response = requests.get(url=url, headers=headers, auth=(
26 | router['user'], router['password']), verify=False).json()
27 |
28 | print(json.dumps(response, indent=2))
29 |
--------------------------------------------------------------------------------
/Python/Networking/IOS-XE/ENAUTOrestconfPOST.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 | router = {
5 | "host": "ios-xe-mgmt-latest.cisco.com",
6 | "port": "9443",
7 | "user": "root",
8 | "password": "D_Vay!_10&"
9 | }
10 |
11 | headers = {
12 | "Accept": "application/yang-data+json",
13 | "Content-Type": "application/yang-data+json"
14 | }
15 |
16 | url = f"https://{router['host']}:{router['port']}/restconf/data/ietf-interfaces:interfaces/interface=Loopback100"
17 |
18 | # payload = {
19 | # "ietf-interfaces:interface": {
20 | # "name": "Loopback100",
21 | # "description": "Added by CBT Nuggets",
22 | # "type": "iana-if-type:softwareLoopback",
23 | # "enabled": True,
24 | # "ietf-ip:ipv4": {
25 | # "address": [
26 | # {
27 | # "ip": "172.16.100.1",
28 | # "netmask": "255.255.255.0"
29 | # }
30 | # ]
31 | # }
32 | # }
33 | # }
34 |
35 | response = requests.delete(url=url, headers=headers, auth=(
36 | router['user'], router['password']), verify=False)
37 |
38 | if response.status_code == 204:
39 | print(response)
40 | print(response.text)
41 |
--------------------------------------------------------------------------------
/Python/Networking/IOS-XE/__pycache__/interfaces.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DataKnox/CodeSamples/8b375eedfca5b9e5d8965cfedbb073dddcaac091/Python/Networking/IOS-XE/__pycache__/interfaces.cpython-37.pyc
--------------------------------------------------------------------------------
/Python/Networking/IOS-XE/ios_config.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | {interface_name}
5 | {interface_desc}
6 | true
7 |
8 |
9 |
--------------------------------------------------------------------------------
/Python/Networking/IOS-XE/netconf ENCOR.py:
--------------------------------------------------------------------------------
1 | from ncclient import manager
2 | # import logging
3 | # logging.basicConfig(level=logging.DEBUG)
4 |
5 | router = {"host": "172.16.1.81", "port": "830",
6 | "username": "cisco", "password": "cisco"}
7 |
8 | with manager.connect(host=router["host"], port=router["port"], username=router["username"], password=router["password"], hostkey_verify=False) as m:
9 | for capability in m.server_capabilities:
10 | print('*' * 50)
11 | print(capability)
12 |
--------------------------------------------------------------------------------
/Python/Networking/IOS-XE/netconf-1.py:
--------------------------------------------------------------------------------
1 | from ncclient import manager
2 |
3 |
4 | router = {"host": "ios-xe-mgmt-latest.cisco.com", "port": "10000",
5 | "username": "developer", "password": "C1sco12345"}
6 |
7 | with manager.connect(host=router["host"], port=router["port"], username=router["username"], password=router["password"], hostkey_verify=False) as m:
8 | m.close_session()
9 |
--------------------------------------------------------------------------------
/Python/Networking/IOS-XE/netconf-2.py:
--------------------------------------------------------------------------------
1 | from ncclient import manager
2 | # import logging
3 | # logging.basicConfig(level=logging.DEBUG)
4 |
5 | router = {"host": "ios-xe-mgmt-latest.cisco.com", "port": "10000",
6 | "username": "developer", "password": "C1sco12345"}
7 |
8 | with manager.connect(host=router["host"], port=router["port"], username=router["username"], password=router["password"], hostkey_verify=False) as m:
9 | for capability in m.server_capabilities:
10 | print('*' * 50)
11 | print(capability)
12 |
--------------------------------------------------------------------------------
/Python/Networking/IOS-XE/netconf-3.py:
--------------------------------------------------------------------------------
1 | from ncclient import manager
2 |
3 | router = {"host": "ios-xe-mgmt-latest.cisco.com", "port": "10000",
4 | "username": "developer", "password": "C1sco12345"}
5 |
6 | netconf_filter = """
7 |
8 |
9 |
10 | GigabitEthernet2
11 |
12 |
13 |
14 |
15 | GigabitEthernet2
16 |
17 |
18 |
19 | """
20 |
21 | with manager.connect(host=router["host"], port=router["port"], username=router["username"], password=router["password"], hostkey_verify=False) as m:
22 | for capability in m.server_capabilities:
23 | print('*' * 50)
24 | print(capability)
25 |
26 | interface_netconf = m.get_config('running', netconf_filter)
27 | print('getting running config')
28 | m.close_session()
29 |
--------------------------------------------------------------------------------
/Python/Networking/IOS-XE/netconf-editconfig.py:
--------------------------------------------------------------------------------
1 | from ncclient import manager
2 | from router_info import router
3 |
4 | config_template = open(
5 | "E:/dev/CodeSamples/Python/Networking/IOS-XE/ios_config.xml").read()
6 |
7 | netconf_config = config_template.format(
8 | interface_name="GigabitEthernet2", interface_desc="daniyal")
9 |
10 | with manager.connect(host=router["host"], port=router["port"], username=router["username"], password=router["password"], hostkey_verify=False) as m:
11 | device_reply = m.edit_config(netconf_config, target="running")
12 | print(device_reply)
13 |
--------------------------------------------------------------------------------
/Python/Networking/IOS-XE/netconf-filter.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | GigabitEthernet2
5 |
6 |
7 |
8 |
9 | GigabitEthernet2
10 |
11 |
12 |
--------------------------------------------------------------------------------
/Python/Networking/IOS-XE/powerbi.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 | from datetime import datetime
4 | from router_info import router
5 | # Router IOS-XE DevNet Sandbox
6 |
7 | # router = {
8 | # 'host': 'ios-xe-mgmt.cisco.com',
9 | # 'port': '9443',
10 | # 'user': 'developer',
11 | # 'pw': 'C1sco12345'
12 | # }
13 |
14 | # Headers
15 | headers = {
16 | 'Content-Type': 'application/yang-data+json',
17 | 'Accept': 'application/yang-data+json'
18 | }
19 |
20 | url = f"https://{router['host']}:{router['port']}/restconf/data/Cisco-IOS-XE-interfaces-oper:interfaces"
21 |
22 | response = requests.get(url=url, headers=headers, auth=(
23 | router['username'], router['password']), verify=False).json()
24 | interfaces = response['Cisco-IOS-XE-interfaces-oper:interfaces']['interface']
25 | for interface in interfaces:
26 | #print(json.dumps(interface, indent=2))
27 | payload = []
28 | body = {
29 | 'int-name': interface['name'],
30 | 'in-packets': int(interface['statistics']['in-unicast-pkts']),
31 | 'out-packets': int(interface['statistics']['out-unicast-pkts']),
32 | 'datetime': datetime.now().isoformat()
33 | }
34 | payload.append(body)
35 | pbi_url = R"PBI URL HERE"
36 | requests.post(url=pbi_url, data=json.dumps(payload))
37 |
--------------------------------------------------------------------------------
/Python/Networking/IOS-XE/pyangdemo.py:
--------------------------------------------------------------------------------
1 | from ncclient import manager
2 | import xml.etree.ElementTree as ET
3 |
4 | # import logging
5 | # logging.basicConfig(level=logging.DEBUG)
6 |
7 | router = {"host": "ios-xe-mgmt-latest.cisco.com", "port": "10000",
8 | "username": "developer", "password": "C1sco12345"}
9 |
10 | with manager.connect(host=router["host"], port=router["port"], username=router["username"], password=router["password"], hostkey_verify=False) as m:
11 | ip_schema = m.get_schema('ietf-ip')
12 | print(ip_schema)
13 | root = ET.fromstring(ip_schema.xml)
14 | yang_tree = list(root)[0].text
15 | output_file = open('ietf-ip.yang', 'w')
16 | output_file.write(yang_tree)
17 | output_file.close()
18 |
--------------------------------------------------------------------------------
/Python/Networking/IOS-XE/pyangint.py:
--------------------------------------------------------------------------------
1 | from ncclient import manager
2 | import xml.etree.ElementTree as ET
3 |
4 | # import logging
5 | # logging.basicConfig(level=logging.DEBUG)
6 |
7 | router = {"host": "ios-xe-mgmt-latest.cisco.com", "port": "10000",
8 | "username": "developer", "password": "C1sco12345"}
9 |
10 | with manager.connect(host=router["host"], port=router["port"], username=router["username"], password=router["password"], hostkey_verify=False) as m:
11 | ip_schema = m.get_schema('ietf-interfaces')
12 | root = ET.fromstring(ip_schema.xml)
13 | yang_tree = list(root)[0].text
14 | output_file = open('ietf-interfaces.yang', 'w')
15 | output_file.write(yang_tree)
16 | output_file.close()
17 |
--------------------------------------------------------------------------------
/Python/Networking/IOS-XE/restconf ENCOR.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 | from pprint import pprint
4 |
5 | # set up connection parameters in a dictionary
6 | router = {"ip": "172.16.1.81", "port": "443",
7 | "user": "cisco", "password": "cisco"}
8 |
9 | # set REST API headers
10 | headers = {"Accept": "application/yang-data+json",
11 | "Content-Type": "application/yang-data+json"}
12 |
13 | url = f"https://{router['ip']}:{router['port']}/restconf/data/Cisco-IOS-XE-interfaces-oper:interfaces/interface=GigabitEthernet1"
14 | # print(url)
15 |
16 | response = requests.get(url, headers=headers, auth=(
17 | router['user'], router['password']), verify=False)
18 |
19 |
20 | api_data = response.json()
21 | print("/" * 50)
22 | pprint(api_data["Cisco-IOS-XE-interfaces-oper:interface"]["description"])
23 | print("/" * 50)
24 | if api_data["Cisco-IOS-XE-interfaces-oper:interface"]["admin-status"] == 'if-state-up':
25 | print('Interface is up')
26 |
--------------------------------------------------------------------------------
/Python/Networking/IOS-XE/restconf-get.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 | # set up connection parameters in a dictionary
5 | router = {"ip": "ios-xe-mgmt.cisco.com", "port": "9443",
6 | "user": "root", "password": "D_Vay!_10&"}
7 |
8 | # set REST API headers
9 | headers = {"Accept": "application/yang-data+json",
10 | "Content-Type": "application/yang-data+json"}
11 |
12 | url = f"https://{router['ip']}:{router['port']}/restconf/data/Cisco-IOS-XE-interfaces-oper:interfaces/interface=GigabitEthernet1"
13 | # print(url)
14 |
15 | response = requests.get(url, headers=headers, auth=(
16 | router['user'], router['password']), verify=False)
17 |
18 |
19 | api_data = response.json()
20 | print("/" * 50)
21 | print(api_data["Cisco-IOS-XE-interfaces-oper:interface"]["description"])
22 | print("/" * 50)
23 | if api_data["Cisco-IOS-XE-interfaces-oper:interface"]["admin-status"] == 'if-state-up':
24 | print('Interface is up')
25 |
--------------------------------------------------------------------------------
/Python/Networking/IOS-XE/router_info.py:
--------------------------------------------------------------------------------
1 | router = {"host": "ios-xe-mgmt-latest.cisco.com",
2 | "port": "10000",
3 | "username": "root",
4 | "password": "D_Vay!_10&"}
5 |
--------------------------------------------------------------------------------
/Python/Networking/IOS-XE/scrapli-yang/nc-rpc.py:
--------------------------------------------------------------------------------
1 | from scrapli_netconf.driver import NetconfScrape
2 |
3 | my_device = {
4 | "host": "10.10.21.15",
5 | "auth_username": "cisco",
6 | "auth_password": "cisco",
7 | "auth_strict_key": False,
8 | "port": 830
9 | }
10 |
11 | conn = NetconfScrape(**my_device)
12 | conn.open()
13 |
14 | rpc_filter = '''
15 |
16 |
17 |
18 | '''
19 |
20 | response = conn.rpc(rpc_filter)
21 | print(response.result)
22 |
--------------------------------------------------------------------------------
/Python/Networking/IOS-XE/scrapli-yang/nc-subtree.py:
--------------------------------------------------------------------------------
1 | from scrapli_netconf.driver import NetconfScrape
2 |
3 | my_device = {
4 | "host": "10.10.21.15",
5 | "auth_username": "cisco",
6 | "auth_password": "cisco",
7 | "auth_strict_key": False,
8 | "port": 830
9 | }
10 |
11 | conn = NetconfScrape(**my_device)
12 | conn.open()
13 |
14 | ospf_filter = """
15 |
16 |
17 |
18 | address-family-ipv4
19 | 16843009
20 |
21 | 0
22 |
23 | GigabitEthernet2
24 |
25 | 2.2.2.2
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 | """
34 |
35 | response = conn.get(
36 | filter_=ospf_filter, filter_type='subtree')
37 | print(response.result)
38 |
--------------------------------------------------------------------------------
/Python/Networking/IOS-XE/scrapli-yang/nc-xpath.py:
--------------------------------------------------------------------------------
1 | from scrapli_netconf.driver import NetconfScrape
2 |
3 | my_device = {
4 | "host": "10.10.21.15",
5 | "auth_username": "cisco",
6 | "auth_password": "cisco",
7 | "auth_strict_key": False,
8 | "port": 830
9 | }
10 |
11 | conn = NetconfScrape(**my_device)
12 | conn.open()
13 |
14 | ospf_xpath = '/ospf-oper-data/ospf-state/ospf-instance[af="address-family-ipv4" and router-id="16843009"]/ospf-area[area-id=0]/ospf-interface[name="GigabitEthernet2"]/ospf-neighbor[neighbor-id="2.2.2.2"]/state'
15 | response = conn.get(
16 | filter_=ospf_xpath, filter_type='xpath')
17 | print(response.result)
18 |
--------------------------------------------------------------------------------
/Python/Networking/IOS-XE/scrapli/mydevice.py:
--------------------------------------------------------------------------------
1 | switch = {
2 | "host": "10.10.10.2",
3 | "auth_username": "knox",
4 | "auth_password": "cisco",
5 | "auth_strict_key": False,
6 | "port": 830
7 | }
8 |
9 | router = {
10 | "host": "10.10.21.15",
11 | "auth_username": "cisco",
12 | "auth_password": "cisco",
13 | "auth_strict_key": False,
14 | "port": 830
15 | }
16 |
--------------------------------------------------------------------------------
/Python/Networking/IOS-XE/scrapli/netconf-subtree.py:
--------------------------------------------------------------------------------
1 | from scrapli_netconf.driver import NetconfScrape
2 | from mydevice import *
3 |
4 | ospf_filter = """
5 |
6 |
7 |
8 | address-family-ipv4
9 | 16843009
10 |
11 | 0
12 |
13 | Loopback0
14 |
15 |
16 |
17 |
18 |
19 |
20 | """
21 |
22 | conn = NetconfScrape(**router)
23 | conn.open()
24 | response = conn.get(
25 | filter_=ospf_filter, filter_type='subtree')
26 | print(response.result)
27 |
--------------------------------------------------------------------------------
/Python/Networking/IOS-XE/scrapli/netconf-xpath.py:
--------------------------------------------------------------------------------
1 | from scrapli_netconf.driver import NetconfScrape
2 | from mydevice import *
3 |
4 | import logging
5 | logging.basicConfig(level=logging.DEBUG)
6 |
7 |
8 | eigrp_filter = '/eigrp-oper-data/eigrp-instance/eigrp-topo/eigrp-network[afi="eigrp-af-ipv4" and ip-prefix="192.168.10.0/24"]/rd-vecmetric'
9 | ospf_filter = '/ospf-oper-data'
10 |
11 | conn = NetconfScrape(**router)
12 | conn.open()
13 | response = conn.get(
14 | filter_=ospf_filter, filter_type='xpath',)
15 | print(response.result)
16 |
--------------------------------------------------------------------------------
/Python/Networking/IOS-XE/scrapli/scrapli-xpathrpc.py:
--------------------------------------------------------------------------------
1 | from scrapli_netconf.driver import NetconfScrape
2 | from mydevice import *
3 |
4 | import logging
5 | logging.basicConfig(level=logging.DEBUG)
6 |
7 | xpath_filter = '''
8 |
9 |
10 |
11 | '''
12 |
13 | conn = NetconfScrape(**router)
14 | conn.open()
15 | response = conn.rpc(
16 | filter_=xpath_filter)
17 | print(response.result)
18 |
--------------------------------------------------------------------------------
/Python/Networking/IOS-XE/scrpli-eigrp.py:
--------------------------------------------------------------------------------
1 | from scrapli_netconf.driver import NetconfScrape
2 | my_device = {
3 | "host": "10.10.10.2",
4 | "auth_username": "knox",
5 | "auth_password": "cisco",
6 | "auth_strict_key": False,
7 | "port": 830
8 | }
9 | conn = NetconfScrape(**my_device)
10 | conn.open()
11 | response = conn.get(
12 | filter_='//eigrp-network[ip-prefix="192.168.10.0/24"]/rd-vecmetric', filter_type="xpath")
13 | print(response.result)
14 |
--------------------------------------------------------------------------------
/Python/Networking/IOS-XE/yangdemo.py:
--------------------------------------------------------------------------------
1 | from ncclient import manager
2 | import xml.etree.ElementTree as ET
3 |
4 | router = {"host": "ios-xe-mgmt-latest.cisco.com", "port": "10000",
5 | "username": "developer", "password": "C1sco12345"}
6 |
7 | with manager.connect(host=router['host'], port=router['port'], username=router['username'], password=router['password'], hostkey_verify=False) as m:
8 | ip_schema = m.get_schema('ietf-yang-types')
9 | root = ET.fromstring(ip_schema.xml)
10 | yang_tree = list(root)[0].text
11 | f = open('ietf-yang-types .yang', 'w')
12 | f.write(yang_tree)
13 | f.close()
14 |
--------------------------------------------------------------------------------
/Python/Networking/IOS/show ints.py:
--------------------------------------------------------------------------------
1 | import os
2 | from dotenv import load_dotenv
3 | from netmiko import ConnectHandler
4 | import json
5 |
6 | load_dotenv()
7 |
8 | user = os.environ.get('username')
9 | pw = os.environ.get('password')
10 | sec = os.environ.get('secret')
11 |
12 | # Connect
13 | switch = {
14 | 'device_type': 'cisco_ios_telnet',
15 | 'ip': '10.10.10.2',
16 | 'username': user,
17 | 'password': pw,
18 | 'secret': sec,
19 | 'port': 23
20 | }
21 |
22 |
23 | try:
24 | c = ConnectHandler(**switch)
25 | c.enable()
26 | interfaces = c.send_command('show interfaces status', use_textfsm=True)
27 | print(json.dumps(interfaces, indent=2))
28 | for interface in interfaces:
29 | if interface['vlan'] == 'trunk':
30 | print(f"{interface['port']} is a trunk")
31 | c.close()
32 | except Exception as e:
33 | print(e)
34 |
--------------------------------------------------------------------------------
/Python/Networking/IOS/show ip int brief.py:
--------------------------------------------------------------------------------
1 | import os
2 | from dotenv import load_dotenv
3 | from netmiko import ConnectHandler
4 | import json
5 |
6 | load_dotenv()
7 |
8 | user = os.environ.get('username')
9 | pw = os.environ.get('password')
10 | sec = os.environ.get('secret')
11 |
12 | # Connect
13 | switch = {
14 | 'device_type': 'cisco_ios_telnet',
15 | 'ip': '10.10.10.2',
16 | 'username': user,
17 | 'password': pw,
18 | 'secret': sec,
19 | 'port': 23
20 | }
21 |
22 |
23 | try:
24 | c = ConnectHandler(**switch)
25 | c.enable()
26 | interfaces = c.send_command('show ip int brief', use_textfsm=True)
27 | #print(json.dumps(interfaces, indent=2))
28 | for interface in interfaces:
29 | if interface['status'] == 'down':
30 | print(f"{interface['intf']} is down!")
31 | c.close()
32 | except Exception as e:
33 | print(e)
34 |
--------------------------------------------------------------------------------
/Python/Networking/IOS/showver.py:
--------------------------------------------------------------------------------
1 | import os
2 | from dotenv import load_dotenv
3 | from netmiko import ConnectHandler
4 | import json
5 |
6 | load_dotenv()
7 |
8 | user = os.environ.get('username')
9 | pw = os.environ.get('password')
10 | sec = os.environ.get('secret')
11 |
12 | # Connect
13 | switch = {
14 | 'device_type': 'cisco_ios_telnet',
15 | 'ip': '10.10.10.2',
16 | 'username': user,
17 | 'password': pw,
18 | 'secret': sec,
19 | 'port': 23
20 | }
21 |
22 |
23 | try:
24 | c = ConnectHandler(**switch)
25 | c.enable()
26 | versions = c.send_command('show version', use_textfsm=True)
27 | #print(json.dumps(versions, indent=2))
28 | uptime = versions[0]['uptime']
29 | print(uptime)
30 | c.disconnect()
31 | except Exception as e:
32 | print(e)
33 |
--------------------------------------------------------------------------------
/Python/Networking/IOS/spann.py:
--------------------------------------------------------------------------------
1 | import os
2 | from dotenv import load_dotenv
3 | from netmiko import ConnectHandler
4 | import json
5 |
6 | load_dotenv()
7 |
8 | user = os.environ.get('username')
9 | pw = os.environ.get('password')
10 | sec = os.environ.get('secret')
11 |
12 | # Connect
13 | switch = {
14 | 'device_type': 'cisco_ios_telnet',
15 | 'ip': '10.10.10.2',
16 | 'username': user,
17 | 'password': pw,
18 | 'secret': sec,
19 | 'port': 23
20 | }
21 |
22 |
23 | try:
24 | c = ConnectHandler(**switch)
25 | c.enable()
26 | stps = c.send_command('show spanning-tree', use_textfsm=True)
27 | print(json.dumps(stps, indent=2))
28 | for stp in stps:
29 | print(' ')
30 | print(
31 | f"{stp['interface']}.{stp['vlan_id']} is currently in role {stp['role']}")
32 | c.disconnect()
33 | except Exception as e:
34 | print(e)
35 |
--------------------------------------------------------------------------------
/Python/Networking/Junos/Untitled-1.py:
--------------------------------------------------------------------------------
1 | import requests
2 |
3 | url = "http://10.10.10.152:8080/rpc/get-interface-information"
4 |
5 | headers = {
6 | 'Accept': "application/xml",
7 | 'Content-Type': "application/xml",
8 | 'Authorization': "Basic a25veDpqdW5pcGVyMQ==",
9 | 'User-Agent': "PostmanRuntime/7.19.0",
10 | 'Cache-Control': "no-cache",
11 | 'Postman-Token': "373d2816-9083-4a32-84e1-aa8acf2b7341,04b4dcb9-d0c8-4c0d-94c2-46ecef4b179b",
12 | 'Host': "10.10.10.152:8080",
13 | 'Accept-Encoding': "gzip, deflate",
14 | 'Connection': "keep-alive",
15 | 'cache-control': "no-cache"
16 | }
17 |
18 | response = requests.request("GET", url, headers=headers)
19 |
20 | print(response.text)
21 |
--------------------------------------------------------------------------------
/Python/Networking/Junos/facts.py:
--------------------------------------------------------------------------------
1 | from jnpr.junos import Device
2 | from pprint import pprint
3 |
4 | device = Device(host='10.10.10.150', user='root', password='')
5 | device.open()
6 | # pprint(device.facts)
7 | print(device.facts['hostname'])
8 |
--------------------------------------------------------------------------------
/Python/Networking/Junos/getconfig.py:
--------------------------------------------------------------------------------
1 | from ncclient import manager
2 | from ncclient.xml_ import *
3 |
4 | # set device configs
5 | switches = [
6 | {"host": "10.10.10.150", "port": "830",
7 | "username": "root", "password": ""},
8 | {"host": "10.10.10.151", "port": "830",
9 | "username": "root", "password": ""}
10 | ]
11 | for switch in switches:
12 | # make initial connection and save session as variable m
13 | with manager.connect(host=switch["host"], port=switch["port"], username=switch["username"], password=switch["password"], hostkey_verify=False, device_params={"name": "junos"}) as m:
14 | # retrieve config in XML format
15 | response = m.get_configuration(format='xml')
16 | host = response.xpath('configuration/system/host-name')[0].text
17 | interfaces = response.xpath('configuration/interfaces/interface')
18 | print('='*15)
19 | print(host)
20 | print('='*15)
21 | for interface in interfaces:
22 | int_name = interface.xpath('name')[0].text
23 | int_unit = interface.xpath('unit/name')[0].text
24 | ip = []
25 | for name in interface.xpath('unit/family/inet/address/name'):
26 | ip.append(name.text)
27 | print(f"{int_name}.{int_unit} {ip}")
28 | # print(response)
29 |
--------------------------------------------------------------------------------
/Python/Networking/Junos/netconf.sh:
--------------------------------------------------------------------------------
1 | ssh root@10.10.10.150 -p 830 -s netconf
--------------------------------------------------------------------------------
/Python/Networking/Junos/pyez-config.py:
--------------------------------------------------------------------------------
1 | from jnpr.junos import Device
2 | from jnpr.junos.utils.config import Config
3 |
4 |
5 | switch = {'host': '10.10.10.150', 'user': 'root', 'pw': ''}
6 |
7 | device = Device(host=switch['host'],
8 | user=switch['user'], password=switch['pw'])
9 | device.open()
10 | config = Config(device)
11 | payload = """vlans{
12 | vlan101{
13 | vlan-id 101;
14 | }
15 | }
16 | """
17 | config.lock()
18 | config.load(payload, format='text')
19 | config.pdiff()
20 | if config.commit_check() == True:
21 | config.commit()
22 | else:
23 | config.rollback()
24 | config.unlock()
25 | device.close()
26 |
--------------------------------------------------------------------------------
/Python/Networking/Junos/pyez-exception.py:
--------------------------------------------------------------------------------
1 | from jnpr.junos import Device
2 | from jnpr.junos.utils.config import Config
3 | from jnpr.junos.exception import *
4 |
5 |
6 | switch = {'host': '10.10.10.150', 'user': 'root', 'pw': 'S0lut1ons'}
7 |
8 | conn = Device(host=switch['host'],
9 | user=switch['user'], password=switch['pw'])
10 | try:
11 | conn.open()
12 | config = Config(conn)
13 | payload = """vlans
14 | vlan101{
15 | vlan-id 101;
16 | }
17 | }
18 | """
19 | config.lock()
20 | config.load(payload, format='text')
21 | config.pdiff()
22 | if config.commit_check():
23 | config.commit()
24 | else:
25 | config.rollback()
26 | config.unlock()
27 |
28 | except ConnectAuthError as error:
29 | print('Authentication error occurred. Check your creds')
30 | print(str(error))
31 | except ConfigLoadError as error:
32 | print(f'Config Load error: {str(error)}')
33 | finally:
34 | conn.close()
35 |
--------------------------------------------------------------------------------
/Python/Networking/Junos/pyez-facts.py:
--------------------------------------------------------------------------------
1 | from jnpr.junos import Device
2 | from pprint import pprint
3 |
4 | switch = {'host': '10.10.10.150', 'user': 'root', 'pw': ''}
5 |
6 | conn = Device(host=switch['host'],
7 | user=switch['user'], password=switch['pw'])
8 |
9 | conn.open()
10 | # pprint(conn.facts)
11 | hostname = conn.facts['hostname']
12 | style = conn.facts['switch_style']
13 | print(f"{hostname} has the style type of {style}")
14 | conn.close()
15 |
--------------------------------------------------------------------------------
/Python/Networking/Junos/pyez-geconfig.py:
--------------------------------------------------------------------------------
1 | from jnpr.junos import Device
2 | from lxml import etree
3 |
4 | with Device(host='10.10.10.152', user='knox', password='juniper1') as dev:
5 | data = dev.rpc.get_config(options={'database': 'committed'})
6 | print(etree.tostring(data, encoding='unicode', pretty_print=True))
7 |
--------------------------------------------------------------------------------
/Python/Networking/Junos/pyez-rpc.py:
--------------------------------------------------------------------------------
1 | from jnpr.junos import Device
2 |
3 | switch = {'host': '10.10.10.151', 'user': 'root', 'pw': 'S0lut1ons'}
4 |
5 | device = Device(host=switch['host'],
6 | user=switch['user'], password=switch['pw'])
7 |
8 | device.open()
9 |
10 | routes_xml = device.rpc.get_route_information(table='inet.0')
11 |
12 | routes = routes_xml.findall('.//rt')
13 |
14 | for route in routes:
15 | if route.findtext('rt-entry/protocol-name') != 'Local':
16 | dest = route.findtext('rt-destination')
17 | via = route.findtext('rt-entry/nh/via')
18 | print(f"{dest} via {via}")
19 |
--------------------------------------------------------------------------------
/Python/Networking/Junos/restapi.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 | url = "http://10.10.10.152:8080/rpc/get-interface-information"
5 |
6 | headers = {
7 | 'Accept': "application/json",
8 | 'Content-Type': "application/xml"
9 | }
10 |
11 | response = requests.get(url, headers=headers, auth=('knox', 'juniper1')).json()
12 |
13 | print(json.dumps(response, indent=2, sort_keys=True))
14 |
--------------------------------------------------------------------------------
/Python/Networking/Junos/rpc_get_sample.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/Python/Networking/Junos/rpc_set_example.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/Python/Networking/Meraki/DEVCORenableSSID.py:
--------------------------------------------------------------------------------
1 | from dotenv import load_dotenv
2 | import requests
3 | import json
4 | import os
5 | from DEVCORgetnets import get_net_id
6 | from DEVCORgetssids import get_ssids
7 |
8 | load_dotenv()
9 |
10 | token = os.environ.get('TOKEN')
11 |
12 | headers = {
13 | "Accept": "application/json",
14 | "Content-Type": "application/json",
15 | "X-Cisco-Meraki-API-Key": token
16 | }
17 |
18 | base_url = "https://api.meraki.com/api/v0"
19 |
20 |
21 | def set_ssids():
22 | net_id = get_net_id()
23 | ssid_data = get_ssids()
24 | ssid_no = ssid_data['id']
25 | if not ssid_data['status']:
26 | print(f"Status is False {ssid_data['status']}")
27 | ssids_url = f'/networks/{net_id}/ssids/{ssid_no}'
28 | payload = {
29 | 'name': ssid_data['name'],
30 | 'enabled': True
31 | }
32 | response = requests.put(
33 | url=f"{base_url}{ssids_url}", headers=headers, data=json.dumps(payload))
34 | # print(response.status_code)
35 | # print(response)
36 | return response
37 |
38 |
39 | if __name__ == "__main__":
40 | resp = set_ssids()
41 | print(resp)
42 |
--------------------------------------------------------------------------------
/Python/Networking/Meraki/DEVCORgetssids.py:
--------------------------------------------------------------------------------
1 | from dotenv import load_dotenv
2 | import requests
3 | import json
4 | import os
5 | from DEVCORgetnets import get_net_id
6 |
7 | load_dotenv()
8 |
9 | token = os.environ.get('TOKEN')
10 |
11 | headers = {
12 | "Accept": "application/json",
13 | "Content-Type": "application/json",
14 | "X-Cisco-Meraki-API-Key": token
15 | }
16 |
17 | base_url = "https://api.meraki.com/api/v0"
18 |
19 |
20 | def get_ssids():
21 | net_id = get_net_id()
22 | ssids_url = f'/networks/{net_id}/ssids'
23 | try:
24 | ssids_response = requests.get(
25 | url=f"{base_url}{ssids_url}", headers=headers)
26 | print(ssids_response)
27 | if ssids_response.status_code == 200:
28 | ssids = json.loads(ssids_response.text)
29 | for ssid in ssids:
30 | # print(ssid)
31 | if ssid['name'] == 'Unconfigured SSID 2':
32 | ssid_details = {}
33 | ssid_details['id'] = ssid['number']
34 | ssid_details['name'] = ssid['name']
35 | ssid_details['status'] = ssid['enabled']
36 | return ssid_details
37 | except Exception as err:
38 | print(err)
39 |
40 |
41 | ssid = get_ssids()
42 | print(ssid)
43 |
--------------------------------------------------------------------------------
/Python/Networking/Meraki/ENAUTOmerakiCRUD.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 | from requests.exceptions import HTTPError
4 |
5 | merakikey = "meraki key"
6 | base_url = 'https://api.meraki.com/api/v0'
7 | endpoint = '/organizations'
8 |
9 | headers = {
10 | 'X-Cisco-Meraki-API-Key': merakikey,
11 | 'Content-Type': 'application/json'
12 | }
13 |
14 | try:
15 | response = requests.get(url=f"{base_url}{endpoint}", headers=headers)
16 | if response.status_code == 200:
17 | orgs = response.json()
18 | for org in orgs:
19 | if org['name'] == 'Knoxs Data':
20 | orgid = org['id']
21 | except Exception as ex:
22 | print(ex)
23 |
24 | endpoint = f"/organizations/{orgid}/networks"
25 |
26 | payload = {
27 | 'name': 'My Demo Net',
28 | 'type': 'appliance switch camera'
29 | }
30 |
31 | try:
32 | response = requests.post(
33 | url=f"{base_url}{endpoint}", headers=headers, data=json.dumps(payload))
34 | if response.status_code == 201:
35 | print(response.text)
36 | except Exception as ex:
37 | print(ex)
38 |
--------------------------------------------------------------------------------
/Python/Networking/Meraki/get licenses.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 | url = "https://dashboard.meraki.com/api/v0/organizations"
5 |
6 | headers = {
7 | 'X-Cisco-Meraki-API-Key': "6bec40cf957de430a6f1f2baa056b99a4fac9ea0",
8 | 'User-Agent': "PostmanRuntime/7.16.3",
9 | 'Accept': "*/*",
10 | 'Cache-Control': "no-cache",
11 | 'Postman-Token': "67a3f4c9-bcb4-43a5-bcde-c05ec3e976af,b27f7dd9-3ebc-4d17-a0a8-d62ab5cafb99",
12 | 'Accept-Encoding': "gzip, deflate",
13 | 'Referer': "https://api.meraki.com/api/v0/organizations",
14 | 'Connection': "keep-alive",
15 | 'cache-control': "no-cache"
16 | }
17 |
18 | response = requests.get(url, headers=headers).json()
19 |
20 | #print(json.dumps(response, indent=2, sort_keys=True))
21 |
22 | for response_org in response:
23 | if response_org['name'] == 'DevNet Sandbox':
24 | orgId = response_org['id']
25 |
26 | net_url = f'{url}/{orgId}/licenses'
27 |
28 | networks = requests.get(net_url, headers=headers).json()
29 | print(json.dumps(networks, indent=2, sort_keys=True))
30 |
--------------------------------------------------------------------------------
/Python/Networking/Meraki/get meraki admins.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 | url = "https://dashboard.meraki.com/api/v0/organizations"
5 |
6 | headers = {
7 | 'X-Cisco-Meraki-API-Key': "6bec40cf957de430a6f1f2baa056b99a4fac9ea0",
8 | 'User-Agent': "PostmanRuntime/7.16.3",
9 | 'Accept': "*/*",
10 | 'Cache-Control': "no-cache",
11 | 'Postman-Token': "67a3f4c9-bcb4-43a5-bcde-c05ec3e976af,b27f7dd9-3ebc-4d17-a0a8-d62ab5cafb99",
12 | 'Accept-Encoding': "gzip, deflate",
13 | 'Referer': "https://api.meraki.com/api/v0/organizations",
14 | 'Connection': "keep-alive",
15 | 'cache-control': "no-cache"
16 | }
17 |
18 | response = requests.get(url, headers=headers).json()
19 |
20 | #print(json.dumps(response, indent=2, sort_keys=True))
21 |
22 | for response_org in response:
23 | if response_org['name'] == 'DevNet Sandbox':
24 | orgId = response_org['id']
25 |
26 | net_url = f'{url}/{orgId}/admins'
27 |
28 | networks = requests.get(net_url, headers=headers).json()
29 | print(json.dumps(networks, indent=2, sort_keys=True))
30 |
--------------------------------------------------------------------------------
/Python/Networking/Meraki/get net traffic.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 | from datetime import datetime
4 |
5 | url = "https://dashboard.meraki.com/api/v0/organizations"
6 |
7 | headers = {
8 | 'X-Cisco-Meraki-API-Key': "6bec40cf957de430a6f1f2baa056b99a4fac9ea0",
9 | 'User-Agent': "PostmanRuntime/7.16.3",
10 | 'Accept': "*/*",
11 | 'Cache-Control': "no-cache",
12 | 'Postman-Token': "67a3f4c9-bcb4-43a5-bcde-c05ec3e976af,b27f7dd9-3ebc-4d17-a0a8-d62ab5cafb99",
13 | 'Accept-Encoding': "gzip, deflate",
14 | 'Referer': "https://api.meraki.com/api/v0/organizations",
15 | 'Connection': "keep-alive",
16 | 'cache-control': "no-cache"
17 | }
18 |
19 | response = requests.get(url, headers=headers).json()
20 |
21 | #print(json.dumps(response, indent=2, sort_keys=True))
22 |
23 | for response_org in response:
24 | if response_org['name'] == 'DevNet Sandbox':
25 | orgId = response_org['id']
26 |
27 | net_url = f'{url}/{orgId}/networks'
28 |
29 | networks = requests.get(net_url, headers=headers).json()
30 | print(networks)
31 | for network in networks:
32 | if network['name'] == 'DNSMB5':
33 | netId = network['id']
34 |
35 | client_url = f'https://dashboard.meraki.com/api/v0/networks/{netId}/traffic?timespan=604800'
36 | clients = requests.get(client_url, headers=headers).json()
37 | print(json.dumps(clients, indent=2, sort_keys=True))
38 |
--------------------------------------------------------------------------------
/Python/Networking/Meraki/get switch settings.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 | from datetime import datetime
4 |
5 | url = "https://dashboard.meraki.com/api/v0/organizations"
6 |
7 | headers = {
8 | 'X-Cisco-Meraki-API-Key': "17d06f8fd988574af1d3280be9bdc9216134524a",
9 | 'User-Agent': "PostmanRuntime/7.16.3",
10 | 'Accept': "*/*",
11 | 'Cache-Control': "no-cache",
12 | 'Postman-Token': "67a3f4c9-bcb4-43a5-bcde-c05ec3e976af,b27f7dd9-3ebc-4d17-a0a8-d62ab5cafb99",
13 | 'Accept-Encoding': "gzip, deflate",
14 | 'Referer': "https://api.meraki.com/api/v0/organizations",
15 | 'Connection': "keep-alive",
16 | 'cache-control': "no-cache"
17 | }
18 |
19 | response = requests.get(url, headers=headers).json()
20 |
21 | #print(json.dumps(response, indent=2, sort_keys=True))
22 |
23 | for response_org in response:
24 | if response_org['name'] == 'Knoxs Data':
25 | orgId = response_org['id']
26 |
27 | net_url = f'{url}/{orgId}/networks'
28 |
29 | networks = requests.get(net_url, headers=headers).json()
30 | # print(networks)
31 | for network in networks:
32 | if network['name'] == 'SoHo':
33 | netId = network['id']
34 |
35 |
36 | client_url = f'https://dashboard.meraki.com/api/v0/networks/{netId}/switch/settings'
37 | clients = requests.get(client_url, headers=headers).json()
38 | print(json.dumps(clients, indent=2))
39 |
--------------------------------------------------------------------------------
/Python/Networking/Meraki/get traffic shaping.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 | url = "https://dashboard.meraki.com/api/v0/organizations"
5 |
6 | headers = {
7 | 'X-Cisco-Meraki-API-Key': "6bec40cf957de430a6f1f2baa056b99a4fac9ea0",
8 | 'User-Agent': "PostmanRuntime/7.16.3",
9 | 'Accept': "*/*",
10 | 'Cache-Control': "no-cache",
11 | 'Postman-Token': "67a3f4c9-bcb4-43a5-bcde-c05ec3e976af,b27f7dd9-3ebc-4d17-a0a8-d62ab5cafb99",
12 | 'Accept-Encoding': "gzip, deflate",
13 | 'Referer': "https://api.meraki.com/api/v0/organizations",
14 | 'Connection': "keep-alive",
15 | 'cache-control': "no-cache"
16 | }
17 |
18 | response = requests.get(url, headers=headers).json()
19 |
20 | #print(json.dumps(response, indent=2, sort_keys=True))
21 |
22 | for response_org in response:
23 | if response_org['name'] == 'DevNet Sandbox':
24 | orgId = response_org['id']
25 |
26 | net_url = f'{url}/{orgId}/networks'
27 |
28 | networks = requests.get(net_url, headers=headers).json()
29 | print(networks)
30 | for network in networks:
31 | if network['name'] == 'DNSMB5':
32 | netId = network['id']
33 |
34 | client_url = f'https://dashboard.meraki.com/api/v0/networks/{netId}/trafficShaping'
35 | clients = requests.get(client_url, headers=headers).json()
36 | print(json.dumps(clients, indent=2, sort_keys=True))
37 |
--------------------------------------------------------------------------------
/Python/Networking/Meraki/getclients.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 | url = "https://dashboard.meraki.com/api/v0/organizations"
5 |
6 | headers = {
7 | 'X-Cisco-Meraki-API-Key': "6bec40cf957de430a6f1f2baa056b99a4fac9ea0",
8 | 'User-Agent': "PostmanRuntime/7.16.3",
9 | 'Accept': "*/*",
10 | 'Cache-Control': "no-cache",
11 | 'Postman-Token': "67a3f4c9-bcb4-43a5-bcde-c05ec3e976af,b27f7dd9-3ebc-4d17-a0a8-d62ab5cafb99",
12 | 'Accept-Encoding': "gzip, deflate",
13 | 'Referer': "https://api.meraki.com/api/v0/organizations",
14 | 'Connection': "keep-alive",
15 | 'cache-control': "no-cache"
16 | }
17 |
18 | response = requests.get(url, headers=headers).json()
19 |
20 | #print(json.dumps(response, indent=2, sort_keys=True))
21 |
22 | for response_org in response:
23 | if response_org['name'] == 'DevNet Sandbox':
24 | orgId = response_org['id']
25 |
26 | net_url = f'{url}/{orgId}/networks'
27 |
28 | networks = requests.get(net_url, headers=headers).json()
29 | print(networks)
30 | for network in networks:
31 | if network['name'] == 'DNSMB3':
32 | netId = network['id']
33 |
34 | client_url = f'https://dashboard.meraki.com/api/v0/networks/{netId}/l3FirewallRules'
35 | clients = requests.get(client_url, headers=headers).json()
36 | print(json.dumps(clients, indent=2, sort_keys=True))
37 |
--------------------------------------------------------------------------------
/Python/Networking/Meraki/getdevices.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 | url = "https://dashboard.meraki.com/api/v0/organizations"
5 |
6 | headers = {
7 | 'X-Cisco-Meraki-API-Key': "6bec40cf957de430a6f1f2baa056b99a4fac9ea0",
8 | 'User-Agent': "PostmanRuntime/7.16.3",
9 | 'Accept': "*/*",
10 | 'Cache-Control': "no-cache",
11 | 'Postman-Token': "67a3f4c9-bcb4-43a5-bcde-c05ec3e976af,b27f7dd9-3ebc-4d17-a0a8-d62ab5cafb99",
12 | 'Accept-Encoding': "gzip, deflate",
13 | 'Referer': "https://api.meraki.com/api/v0/organizations",
14 | 'Connection': "keep-alive",
15 | 'cache-control': "no-cache"
16 | }
17 |
18 | response = requests.get(url, headers=headers).json()
19 |
20 | #print(json.dumps(response, indent=2, sort_keys=True))
21 |
22 | for response_org in response:
23 | if response_org['name'] == 'DevNet Sandbox':
24 | orgId = response_org['id']
25 |
26 | net_url = f'{url}/{orgId}/networks'
27 |
28 | networks = requests.get(net_url, headers=headers).json()
29 | for network in networks:
30 | if network['name'] == 'DNSMB2':
31 | netId = network['id']
32 |
33 | dev_url = f'https://dashboard.meraki.com/api/v0/networks/{netId}/devices'
34 | devices = requests.get(dev_url, headers=headers).json()
35 | print(json.dumps(devices, indent=2, sort_keys=True))
36 |
--------------------------------------------------------------------------------
/Python/Networking/Meraki/getnetworks.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 | url = "https://dashboard.meraki.com/api/v0/organizations"
5 |
6 | headers = {
7 | 'X-Cisco-Meraki-API-Key': "6bec40cf957de430a6f1f2baa056b99a4fac9ea0",
8 | 'User-Agent': "PostmanRuntime/7.16.3",
9 | 'Accept': "*/*",
10 | 'Cache-Control': "no-cache",
11 | 'Postman-Token': "67a3f4c9-bcb4-43a5-bcde-c05ec3e976af,b27f7dd9-3ebc-4d17-a0a8-d62ab5cafb99",
12 | 'Accept-Encoding': "gzip, deflate",
13 | 'Referer': "https://api.meraki.com/api/v0/organizations",
14 | 'Connection': "keep-alive",
15 | 'cache-control': "no-cache"
16 | }
17 |
18 | response = requests.get(url, headers=headers).json()
19 |
20 | #print(json.dumps(response, indent=2, sort_keys=True))
21 |
22 | for response_org in response:
23 | if response_org['name'] == 'DevNet Sandbox':
24 | orgId = response_org['id']
25 |
26 | net_url = f'{url}/{orgId}/networks'
27 |
28 | networks = requests.get(net_url, headers=headers).json()
29 | print(json.dumps(networks, indent=2, sort_keys=True))
30 |
--------------------------------------------------------------------------------
/Python/Networking/Meraki/getvlans.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 | from dotenv import load_dotenv
4 | import os
5 | load_dotenv()
6 |
7 | url = "https://dashboard.meraki.com/api/v0/organizations"
8 | token = os.environ.get('merakey')
9 | headers = {
10 | 'X-Cisco-Meraki-API-Key': token,
11 | 'User-Agent': "PostmanRuntime/7.16.3",
12 | 'Accept': "*/*",
13 | 'Cache-Control': "no-cache",
14 | 'Postman-Token': "67a3f4c9-bcb4-43a5-bcde-c05ec3e976af,b27f7dd9-3ebc-4d17-a0a8-d62ab5cafb99",
15 | 'Accept-Encoding': "gzip, deflate",
16 | 'Referer': "https://api.meraki.com/api/v0/organizations",
17 | 'Connection': "keep-alive",
18 | 'cache-control': "no-cache"
19 | }
20 |
21 | response = requests.get(url, headers=headers).json()
22 |
23 | for response_org in response:
24 | if response_org['name'] == 'CBT Nuggets':
25 | orgId = response_org['id']
26 |
27 | net_url = f'{url}/{orgId}/networks'
28 |
29 | networks = requests.get(net_url, headers=headers).json()
30 | print(json.dumps(networks, indent=2, sort_keys=True))
31 |
32 | vlan_url = f'https://dashboard.meraki.com/api/v0/networks/{netId}/vlans'
33 | vlans = requests.get(vlan_url, headers=headers).json()
34 | print(json.dumps(vlans, indent=2, sort_keys=True))
35 |
--------------------------------------------------------------------------------
/Python/Networking/NAPALM/napalmdemo.py:
--------------------------------------------------------------------------------
1 | import napalm
2 | import json
3 |
4 | driver = napalm.get_network_driver('junos')
5 |
6 | device = driver(hostname='10.10.10.152', username='knox', password='juniper1')
7 | device.open()
8 | print(device.get_config(retrieve='running', full=False))
9 | print(device.get_environment())
10 | device.close()
11 |
--------------------------------------------------------------------------------
/Python/Networking/NSO/bash commands.sh:
--------------------------------------------------------------------------------
1 | # INSTALL DEPENDENCIES FOR UBUNTU 18.04
2 | sudo apt update
3 |
4 | sudo apt install python
5 |
6 | sudo apt install default-jdk
7 |
8 | sudo apt install xsltproc
9 |
10 | sudo apt install make
11 |
12 | sudo apt install ant
13 |
14 | # DOWNLOAD AND EXTRACT NSO
15 | # DOWNLOAD LINK FOR UBUNTU https://developer.cisco.com/fileMedia/download/119b2bc7-dbf6-49a1-974d-0a5610e41390/
16 | # UNPACK
17 | sh nso-5.1.0.1.linux.x86_64.signed.bin
18 | #INSTALL
19 | sh nso-5.1.0.1.linux.x86_64.installer.bin $HOME/nso-5.1 --local-install
20 |
21 | cd $home
22 | # THIS NEXT COMMAND ALLOWS YOU TO USE NCS COMMANDS.
23 | # DO NOT SKIP
24 | source nso-5.1/ncsrc
25 | # Make sure NCS knows which directory to run sims in. Create ncs-run if this errors
26 | ncs-setup --dest $HOME/ncs-run
27 | #Copy Cisco images and configs
28 | cp -R nso-5.1/packages/neds/cisco-ios-cli-3.0 ncs-run/packages/cisco-ios-cli-3.0
29 |
30 | cd ncs-run
31 |
32 | ncs-netsim create-network $NCS_DIR/packages/neds/cisco-ios-cli-3.0 3 c
33 |
34 | ncs-netsim start
35 | # Enter the CLI for router c1
36 | ncs-netsim cli-i c1
37 |
38 | en
39 |
40 | show run
41 |
42 | exit
43 | # Create the base configs for NSO based on the generated router configs
44 | ncs-setup --netsim-dir ./netsim --dest .
45 |
46 | ncs
47 |
48 | ncs_cli -u admin
49 |
50 | show configuration devices device
51 | # Structured data!!
52 | exit
--------------------------------------------------------------------------------
/Python/Networking/NSO/nso.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 | # Dont forget sudo ufw allow 8080
5 | url_base = 'http://10.10.21.32:8080/api'
6 | auth = ("admin", "admin")
7 |
8 | # Other useful headers
9 |
10 | # 'application/vnd.yang.api+json',
11 | # 'application/vnd.yang.datastore+json',
12 | # 'application/vnd.yang.data+json',
13 |
14 |
15 | headers = {'Accept': 'application/vnd.yang.collection+json'}
16 |
17 | # Get request to NSO
18 | response = requests.get(
19 | f'{url_base}/running/devices/device', auth=auth, headers=headers).json()
20 | # print(json.dumps(response, indent=2, sort_keys=True))
21 |
22 | # Parse out devices from response body
23 | devices = response['collection']['tailf-ncs:device']
24 | for device in devices:
25 | print(f"Name: {device['name']}")
26 | print(f"IP: {device['address']}")
27 | print(f"SSH Port: {device['port']}")
28 | print(f"Auth Group: {device['authgroup']}")
29 | # print(device)
30 | print(" ")
31 |
--------------------------------------------------------------------------------
/Python/Networking/NX-API/nxapi.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 | url = "https://sbx-nxos-mgmt.cisco.com/ins"
5 | switchuser = "admin"
6 | switchpassword = "Admin_1234!"
7 |
8 | myheaders = {"content-type": "application/json"}
9 | payload = {
10 | "ins_api": {
11 | "version": "1.0",
12 | "type": "cli_show",
13 | "chunk": "0",
14 | "sid": "1",
15 | "input": "show ip int brief",
16 | "output_format": "json",
17 | }
18 | }
19 | response = requests.post(
20 | url,
21 | data=json.dumps(payload),
22 | headers=myheaders,
23 | auth=(switchuser, switchpassword),
24 | verify=False,
25 | ).json()
26 |
27 | print(json.dumps(response, indent=2, sort_keys=True))
28 |
--------------------------------------------------------------------------------
/Python/Networking/Nornir/bgp_deploy.py:
--------------------------------------------------------------------------------
1 | from nornir_pyez.plugins.tasks import *
2 | from nornir import InitNornir
3 | from nornir_utils.plugins.functions import print_result
4 | from nornir.core.filter import F
5 | import os
6 |
7 | script_dir = os.path.dirname(os.path.realpath(__file__))
8 |
9 | nr = InitNornir(config_file=f"{script_dir}/config.yml")
10 |
11 | junos_devices = nr.filter(F(node_type="router"))
12 |
13 |
14 | def bgp_deploy(task):
15 | ints = task.run(name='Collecting Interfaces', task=pyez_int_terse)
16 | neighbors = task.run(name='getting IS-IS neighbors',
17 | task=pyez_rpc, func='get-isis-layer2-map-information')
18 |
19 |
20 | response = junos_devices.run(task=bgp_deploy)
21 | print_result(response)
22 |
--------------------------------------------------------------------------------
/Python/Networking/Nornir/bgp_options.j2:
--------------------------------------------------------------------------------
1 |
2 |
3 | 7.7.7.7
4 |
5 | 100
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Python/Networking/Nornir/bgp_template.j2:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | int-100
6 | internal
7 |
8 | 172.16.57.5
9 | 100
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/Python/Networking/Nornir/clean_ospf.py:
--------------------------------------------------------------------------------
1 | from nornir import InitNornir
2 | from nornir_scrapli.tasks import netconf_get
3 | from nornir_utils.plugins.functions import print_result
4 | import xmltodict
5 | import os
6 | import logging
7 |
8 | script_dir = os.path.dirname(os.path.realpath(__file__))
9 |
10 | nr = InitNornir(config_file=f"{script_dir}/config.yml")
11 |
12 |
13 | ospf_xpath = '//ospf-neighbor/state'
14 |
15 |
16 | def ospf_nbr_state(task):
17 | result = task.run(task=netconf_get, filter_type='xpath',
18 | filter_=ospf_xpath, severity_level=logging.DEBUG)
19 | return result.result
20 |
21 |
22 | results = nr.run(task=ospf_nbr_state)
23 | print_result(results)
24 |
--------------------------------------------------------------------------------
/Python/Networking/Nornir/config.yml:
--------------------------------------------------------------------------------
1 | ---
2 | inventory:
3 | plugin: YAMLInventory
4 | options:
5 | host_file: '/mnt/c/Code/CodeSamples/Python/Networking/Nornir/hosts/hosts.yml'
6 | group_file: '/mnt/c/Code/CodeSamples/Python/Networking/Nornir/groups/groups.yml'
7 | defaults_file: '/mnt/c/Code/CodeSamples/Python/Networking/Nornir/defaults/defaults.yml'
8 |
9 | runner:
10 | plugin: threaded
11 | options:
12 | num_workers: 10
--------------------------------------------------------------------------------
/Python/Networking/Nornir/defaults/default.yml:
--------------------------------------------------------------------------------
1 | ---
2 | username: 'cisco'
--------------------------------------------------------------------------------
/Python/Networking/Nornir/del_ospf.py:
--------------------------------------------------------------------------------
1 | from nornir_pyez.plugins.tasks import pyez_config, pyez_diff, pyez_commit
2 | from nornir import InitNornir
3 | from nornir_utils.plugins.functions import print_result
4 | from nornir.core.filter import F
5 | import os
6 |
7 | script_dir = os.path.dirname(os.path.realpath(__file__))
8 |
9 | nr = InitNornir(config_file=f"{script_dir}/config.yml")
10 |
11 | junos_devices = nr.filter(F(node_type="router"))
12 |
13 |
14 | payload = "delete protocols isis"
15 |
16 | send_result = junos_devices.run(
17 | task=pyez_config, payload=payload, data_format='set', commit_now=True)
18 | print_result(send_result)
19 |
--------------------------------------------------------------------------------
/Python/Networking/Nornir/groups/groups.yml:
--------------------------------------------------------------------------------
1 | ---
2 | cisco_group:
3 | username: 'cisco'
4 | password: 'cisco'
5 | connection_options:
6 | scrapli:
7 | platform: cisco_iosxe
8 | port: 22
9 | extras:
10 | ssh_config_file: True
11 | auth_strict_key: False
12 | scrapli_netconf:
13 | port: 830
14 | extras:
15 | ssh_config_file: True
16 | auth_strict_key: False
17 |
18 | junos_group:
19 | username: 'knox'
20 | password: 'juniper1'
21 | platform: junos
--------------------------------------------------------------------------------
/Python/Networking/Nornir/interfaces.j2:
--------------------------------------------------------------------------------
1 |
2 | {% for intf in interfaces -%}
3 |
4 |
5 | {{ intf }}
6 |
7 | 0
8 |
9 |
10 | {{ interfaces[intf].ipv4_address }}
11 |
12 |
13 |
14 |
15 |
16 |
17 | {% endfor %}
18 |
--------------------------------------------------------------------------------
/Python/Networking/Nornir/isis_config.j2:
--------------------------------------------------------------------------------
1 |
2 | {% for intf in isis_int -%}
3 |
4 |
5 |
6 | {{ intf }}
7 | {% if isis_int[intf].level == 1 -%}
8 |
9 | 2
10 |
11 |
12 | {%- elif isis_int[intf].level == 2 -%}
13 |
14 | 1
15 |
16 |
17 | {% endif %}
18 |
19 |
20 |
21 | {% endfor %}
22 |
--------------------------------------------------------------------------------
/Python/Networking/Nornir/isis_interfaces.j2:
--------------------------------------------------------------------------------
1 |
2 |
3 | {% for intf in isis_int -%}
4 |
5 |
6 | {{ intf[:-2] }}
7 |
8 | 0
9 |
10 |
11 | {% if intf == 'lo0.0' -%}
12 |
13 | {{ isis_int[intf].net }}
14 |
15 | {% endif %}
16 |
17 |
18 |
19 |
20 |
21 | {% endfor %}
22 |
--------------------------------------------------------------------------------
/Python/Networking/Nornir/juniperfacts.py:
--------------------------------------------------------------------------------
1 | from nornir_pyez.plugins.tasks import pyez_facts
2 | from nornir import InitNornir
3 | from nornir_utils.plugins.functions import print_result
4 | from nornir.core.filter import F
5 | import os
6 |
7 | script_dir = os.path.dirname(os.path.realpath(__file__))
8 |
9 | nr = InitNornir(config_file=f"{script_dir}/config.yml")
10 |
11 | junos_devices = nr.filter(F(platform="junos"))
12 |
13 | send_result = junos_devices.run(task=pyez_facts)
14 | print_result(send_result)
15 |
--------------------------------------------------------------------------------
/Python/Networking/Nornir/junosintterse.py:
--------------------------------------------------------------------------------
1 | from nornir_pyez.plugins.tasks import pyez_int_terse
2 | from nornir import InitNornir
3 | from nornir_utils.plugins.functions import print_result
4 | from nornir.core.filter import F
5 | import os
6 |
7 | script_dir = os.path.dirname(os.path.realpath(__file__))
8 |
9 | nr = InitNornir(config_file=f"{script_dir}/config.yml")
10 |
11 | junos_devices = nr.filter(F(platform="junos"))
12 |
13 | send_result = junos_devices.run(task=pyez_int_terse)
14 | print_result(send_result)
15 |
--------------------------------------------------------------------------------
/Python/Networking/Nornir/junospf.py:
--------------------------------------------------------------------------------
1 | from nornir_pyez.plugins.tasks import pyez_config, pyez_facts
2 | from nornir import InitNornir
3 | from nornir_utils.plugins.functions import print_result
4 | from nornir.core.filter import F
5 | import os
6 |
7 | script_dir = os.path.dirname(os.path.realpath(__file__))
8 |
9 | nr = InitNornir(config_file=f"{script_dir}/config.yml")
10 |
11 | junos_devices = nr.filter(F(platform="junos"))
12 |
13 | xml_payload = """
14 |
15 |
16 |
17 | 0.0.0.0
18 |
19 | ge-0/0/0.0
20 | 200
21 |
22 |
23 |
24 |
25 |
26 | """
27 |
28 | send_result = junos_devices.run(
29 | task=pyez_config, payload=xml_payload, data_format='xml', commit_now=True)
30 | print_result(send_result)
31 |
--------------------------------------------------------------------------------
/Python/Networking/Nornir/lacp_ints.j2:
--------------------------------------------------------------------------------
1 |
2 | {% for intf in lacp_int_name -%}
3 |
4 |
5 | {{ intf }}
6 | {% if node_type == 'vQFX-switch' -%}
7 |
8 |
9 | ae0
10 |
11 |
12 | {%- elif node_type == 'EX-switch' -%}
13 |
14 |
15 | ae0
16 |
17 |
18 | {% endif %}
19 |
20 |
21 | {% endfor %}
22 |
--------------------------------------------------------------------------------
/Python/Networking/Nornir/nornir.log:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DataKnox/CodeSamples/8b375eedfca5b9e5d8965cfedbb073dddcaac091/Python/Networking/Nornir/nornir.log
--------------------------------------------------------------------------------
/Python/Networking/Nornir/rpctest.py:
--------------------------------------------------------------------------------
1 | from nornir_pyez.plugins.tasks import pyez_rpc
2 | import os
3 | from nornir import InitNornir
4 | from nornir_utils.plugins.functions import print_result
5 | from rich import print
6 |
7 | script_dir = os.path.dirname(os.path.realpath(__file__))
8 |
9 | nr = InitNornir(config_file=f"{script_dir}/config.yml")
10 |
11 | # xpath = 'interfaces/interface'
12 | # xml = ''
13 | # database = 'committed'
14 | extras = {
15 | "level-extra": "detail",
16 | "interface-name": "ge-0/0/0"
17 | }
18 |
19 | response = nr.run(
20 | task=pyez_rpc, func='get-interface-information', extras=extras)
21 |
22 | # response is an AggregatedResult, which behaves like a list
23 | # there is a response object for each device in inventory
24 | devices = []
25 | for dev in response:
26 | print(response[dev].result)
27 |
--------------------------------------------------------------------------------
/Python/Networking/Nornir/shisisnei.py:
--------------------------------------------------------------------------------
1 | from scrapli.driver.core import IOSXEDriver
2 | from ttp import ttp
3 |
4 |
5 | ttp_template = """
6 | {{hostname}} {{l}} {{int}} {{nei_ip | IP}} {{state}} {{hold}} {{cir}}
7 | """
8 |
9 | my_device = {
10 | "host": "10.10.21.121",
11 | "auth_username": "cisco",
12 | "auth_password": "cisco",
13 | "auth_strict_key": False,
14 | }
15 |
16 | conn = IOSXEDriver(**my_device)
17 | conn.open()
18 | response = conn.send_command("show isis nei")
19 | print(response.result)
20 | data_to_parse = response.result
21 | # create parser object and parse data using template:
22 | parser = ttp(data=data_to_parse, template=ttp_template)
23 | parser.parse()
24 |
25 | # print result in JSON format
26 | results = parser.result(format='json')[0]
27 | print(results)
28 |
--------------------------------------------------------------------------------
/Python/Networking/Nornir/thirty_one_maker.py:
--------------------------------------------------------------------------------
1 | import ipaddress
2 | import requests
3 | from art import *
4 |
5 | # base_net = ipaddress.ip_network('192.168.1.0/24')
6 | # subnets = list(base_net.subnets(new_prefix=31))
7 | # subnets = subnets[1:-1]
8 | # for subnet in subnets:
9 | # print(subnet)
10 | tprint("Data Knox")
11 |
--------------------------------------------------------------------------------
/Python/Networking/PyATSGenie/testbed.yml:
--------------------------------------------------------------------------------
1 | # Example
2 |
3 | testbed:
4 | name: IOS_Testbed
5 | tacacs:
6 | username: knoxlab
7 | passwords:
8 | tacacs:
9 | enable:
10 | devices:
11 | knoxlabCisco: # <----- much match to your device hostname in the prompt
12 | os: ios
13 | type: ios
14 | connections:
15 | a:
16 | protocol: telnet
17 | ip: 10.10.10.2
18 | port: 23
19 | topology:
20 | ios-1:
21 | interfaces:
22 | Vlan1:
23 | ipv4: 10.10.10.2/24
24 | ipv6: ''
25 | link: link-1
26 | type: ethernet
--------------------------------------------------------------------------------
/Python/Networking/PyNTC/junos.py:
--------------------------------------------------------------------------------
1 | from pyntc import ntc_device
2 | from ntc_templates.parse import parse_output
3 | import json
4 | # device types =
5 | # cisco_ios_ssh
6 | # cisco_nxos_nxapi
7 | # juniper_junos_netconf
8 | srx = ntc_device(host='10.10.10.152', username='knox',
9 | password='juniper1', device_type='juniper_junos_netconf')
10 |
11 | response = srx.show('show interfaces')
12 |
13 | print(response)
14 |
--------------------------------------------------------------------------------
/Python/Networking/SDWAN/ENAUTOauthentication.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 | base_url = "https://sandboxsdwan.cisco.com:8443/"
5 | auth_endpoint = "j_security_check"
6 |
7 | login_body = {
8 | "j_username": "devnetuser",
9 | "j_password": "Cisco123!"
10 | }
11 |
12 | sesh = requests.session()
13 | login_response = sesh.post(
14 | url=f"{base_url}{auth_endpoint}", data=login_body, verify=False)
15 |
16 | if not login_response.ok or login_response.text:
17 | print('login failed')
18 | import sys
19 | sys.exit(1)
20 | else:
21 | print('login succeeded')
22 |
--------------------------------------------------------------------------------
/Python/Networking/SDWAN/ENAUTOcertmgmt.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 | import urllib3
4 | urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
5 |
6 | base_url = "https://10.10.20.90/"
7 | auth_endpoint = "j_security_check"
8 |
9 | login_body = {
10 | "j_username": "admin",
11 | "j_password": "admin"
12 | }
13 |
14 | sesh = requests.session()
15 | login_response = sesh.post(
16 | url=f"{base_url}{auth_endpoint}", data=login_body, verify=False)
17 |
18 | if not login_response.ok or login_response.text:
19 | print('login failed')
20 | import sys
21 | sys.exit(1)
22 | else:
23 | print('login succeeded')
24 |
25 | cert_endpoint = "dataservice/certificate/vsmart/list"
26 |
27 | headers = {
28 | "Accept": "application/json"
29 | }
30 |
31 | # response = sesh.get(url=f"{base_url}{cert_endpoint}", verify=False).json()
32 |
33 | # print(json.dumps(response, indent=2))
34 |
35 | root_endpoint = "dataservice/certificate/rootcertificate"
36 |
37 | response = sesh.get(url=f"{base_url}{root_endpoint}",
38 | headers=headers, verify=False).json()
39 |
40 | print(json.dumps(response, indent=2))
41 |
--------------------------------------------------------------------------------
/Python/Networking/SDWAN/ENAUTOdeviceinventory.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 | base_url = "https://sandboxsdwan.cisco.com:8443/"
5 | auth_endpoint = "j_security_check"
6 |
7 | login_body = {
8 | "j_username": "devnetuser",
9 | "j_password": "Cisco123!"
10 | }
11 |
12 | sesh = requests.session()
13 | login_response = sesh.post(
14 | url=f"{base_url}{auth_endpoint}", data=login_body, verify=False)
15 |
16 | if not login_response.ok or login_response.text:
17 | print('login failed')
18 | import sys
19 | sys.exit(1)
20 | else:
21 | print('login succeeded')
22 |
23 | device_endpoint = "dataservice/device/monitor"
24 |
25 | device_response = sesh.get(
26 | url=f"{base_url}{device_endpoint}", verify=False).json()
27 |
28 | print(json.dumps(device_response, indent=2))
29 |
--------------------------------------------------------------------------------
/Python/Networking/SDWAN/ENAUTOgetdata.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 | import urllib3
4 | urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
5 |
6 | base_url = "https://10.10.20.90/"
7 | auth_endpoint = "j_security_check"
8 |
9 | login_body = {
10 | "j_username": "admin",
11 | "j_password": "admin"
12 | }
13 |
14 | sesh = requests.session()
15 | login_response = sesh.post(
16 | url=f"{base_url}{auth_endpoint}", data=login_body, verify=False)
17 |
18 | if not login_response.ok or login_response.text:
19 | print('login failed')
20 | import sys
21 | sys.exit(1)
22 | else:
23 | print('login succeeded')
24 |
25 | cert_status = "dataservice/certificate/stats/summary"
26 |
27 | # response = sesh.get(url=f"{base_url}{cert_status}", verify=False).json()
28 |
29 | # print(json.dumps(response, indent=2))
30 |
31 | alarm_counter = 'dataservice/alarms/count'
32 | # response = sesh.get(url=f"{base_url}{alarm_counter}", verify=False).json()
33 |
34 | # print(json.dumps(response, indent=2))
35 |
36 | tunnel_endpoint = 'dataservice/device/tunnel/statistics?deviceId=4.4.4.61'
37 |
38 | response = sesh.get(url=f"{base_url}{tunnel_endpoint}", verify=False).json()
39 |
40 | print(json.dumps(response, indent=2))
41 |
--------------------------------------------------------------------------------
/Python/Networking/SDWAN/ENAUTOgettemplates.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 | base_url = "https://sandboxsdwan.cisco.com:8443/"
5 | auth_endpoint = "j_security_check"
6 |
7 | login_body = {
8 | "j_username": "devnetuser",
9 | "j_password": "Cisco123!"
10 | }
11 |
12 | sesh = requests.session()
13 | login_response = sesh.post(
14 | url=f"{base_url}{auth_endpoint}", data=login_body, verify=False)
15 |
16 | if not login_response.ok or login_response.text:
17 | print('login failed')
18 | import sys
19 | sys.exit(1)
20 | else:
21 | print('login succeeded')
22 |
23 | template_url = "dataservice/template/feature?templateType=aaa"
24 |
25 | template_response = sesh.get(
26 | url=f"{base_url}{template_url}", verify=False).json()['data']
27 |
28 | print(json.dumps(template_response, indent=2))
29 |
--------------------------------------------------------------------------------
/Python/Networking/SDWAN/ENSDWI/datetimehandler.py:
--------------------------------------------------------------------------------
1 | import time
2 | from datetime import datetime
3 |
4 |
5 | def epochHandler(epoch):
6 | epoch = epochFormatter(epoch)
7 | eventTime = datetime.fromtimestamp(epoch)
8 | now = datetime.now()
9 | #print(eventTime.strftime('%c')+' '+now.strftime('%c'))
10 | # print(now-eventTime)
11 | return(abs(now-eventTime).days)
12 |
13 |
14 | def epochFormatter(epoch):
15 | epoch = str(epoch)
16 | epoch = epoch[:10]
17 | epoch = int(epoch)
18 | return epoch
19 |
20 |
21 | def epochTableFormatter(epoch):
22 | epoch = str(epoch)
23 | epoch = epoch[:10]
24 | epoch = int(epoch)
25 | eventTime = datetime.fromtimestamp(epoch)
26 | return eventTime
27 |
--------------------------------------------------------------------------------
/Python/Networking/SDWAN/ENSDWI/ensdwiauth.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 |
5 | def getAuth(url, username, password, port=8443):
6 | login_body = {
7 | "j_username": username,
8 | "j_password": password
9 | }
10 | base_url = f"{url}:{port}/"
11 | auth_endpoint = "j_security_check"
12 | sesh = requests.session()
13 | login_response = sesh.post(
14 | url=f"{base_url}{auth_endpoint}", data=login_body, verify=False)
15 |
16 | if not login_response.ok or login_response.text:
17 | print('login failed')
18 | import sys
19 | sys.exit(1)
20 | else:
21 | print('login succeeded')
22 | return sesh
23 |
--------------------------------------------------------------------------------
/Python/Networking/SDWAN/ENSDWI/ensdwibfdstats.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 | import urllib3
4 |
5 | urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
6 |
7 |
8 | def getBfdStats(url, session):
9 | bfdstats_endpoint = "dataservice/statistics/bfd"
10 | sesh = session
11 | bfdstats = sesh.get(
12 | url=f"{url}{bfdstats_endpoint}", verify=False).json()['data']
13 |
14 | # print(bfdstats.text)
15 | return bfdstats
16 |
--------------------------------------------------------------------------------
/Python/Networking/SDWAN/ENSDWI/ensdwicontrolconn.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 | import urllib3
4 |
5 | urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
6 |
7 |
8 | def getControlConnections(url, session, device_id):
9 | controlconn_endpoint = f"dataservice/device/control/connections?deviceId={device_id}"
10 | sesh = session
11 | controlconn = sesh.get(
12 | url=f"{url}{controlconn_endpoint}", verify=False).json()
13 |
14 | #print(json.dumps(events, indent=2))
15 | return controlconn
16 |
--------------------------------------------------------------------------------
/Python/Networking/SDWAN/ENSDWI/ensdwidevices.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 | from ensdwiauth import getAuth
4 | import urllib3
5 | urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
6 |
7 |
8 | def getDevices(url, session):
9 | device_endpoint = "dataservice/device/monitor"
10 | sesh = session
11 | devices = sesh.get(
12 | url=f"{url}{device_endpoint}", verify=False).json()
13 |
14 | #print(json.dumps(devices, indent=2))
15 | return devices
16 |
--------------------------------------------------------------------------------
/Python/Networking/SDWAN/ENSDWI/ensdwievents.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 | import urllib3
4 |
5 | urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
6 |
7 |
8 | def getEvents(url, session):
9 | events_endpoint = "dataservice/event"
10 | sesh = session
11 | events = sesh.get(
12 | url=f"{url}{events_endpoint}", verify=False).json()
13 |
14 | #print(json.dumps(events, indent=2))
15 | return events
16 |
--------------------------------------------------------------------------------
/Python/Networking/SDWAN/ENSDWI/ensdwitunnelstats.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 | import urllib3
4 |
5 | urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
6 |
7 |
8 | def getTunnelStats(url, session, device_id):
9 | tunnelstats_endpoint = f"dataservice/device/tunnel/statistics?deviceId={device_id}"
10 | sesh = session
11 | tunnelstats = sesh.get(
12 | url=f"{url}{tunnelstats_endpoint}", verify=False).json()
13 |
14 | #print(json.dumps(events, indent=2))
15 | return tunnelstats
16 |
--------------------------------------------------------------------------------
/Python/Networking/Security/ASA.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 |
4 | url = "https://172.16.1.131/api/routing/static"
5 |
6 | headers = {
7 | 'Content-Type': 'application/json',
8 | 'Accept': 'application/json'
9 | }
10 |
11 | userpw = ('cisco', 'cisco')
12 |
13 | get_response = requests.get(
14 | url, headers=headers, auth=userpw, verify=False).json()['items']
15 |
16 | print(json.dumps(get_response, indent=2, sort_keys=True))
17 |
--------------------------------------------------------------------------------
/Python/Networking/Security/fmc access pol assign.py:
--------------------------------------------------------------------------------
1 | import json
2 | import sys
3 | import requests
4 | import urllib3
5 | urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
6 |
7 | url = "https://fmcrestapisandbox.cisco.com"
8 | login_url = '/api/fmc_platform/v1/auth/generatetoken'
9 | headers = {'Content-Type': 'application/json'}
10 | user = 'knox'
11 | pw = 'BtNdJM9k'
12 |
13 |
14 | login_response = requests.post(
15 | f'{url}{login_url}', auth=(user, pw), verify=False)
16 | # Parse out the headers
17 | resp_headers = login_response.headers
18 | # Grab the token from the response headers
19 | token = resp_headers.get('X-auth-access-token', default=None)
20 | # Set the token in the headers to be used in the next call
21 | headers['X-auth-access-token'] = token
22 |
23 | # Get Access Control Policies
24 | ap_url = '/api/fmc_config/v1/domain/e276abec-e0f2-11e3-8169-6d9ed49b625f/policy/accesspolicies'
25 | ap_response = requests.get(
26 | f'{url}{ap_url}', headers=headers, verify=False).json()
27 | print(json.dumps(ap_response, indent=2, sort_keys=True))
28 |
--------------------------------------------------------------------------------
/Python/Networking/Security/fmc get apps.py:
--------------------------------------------------------------------------------
1 | import json
2 | import sys
3 | import requests
4 |
5 | # Set up variables
6 | url = "https://fmcrestapisandbox.cisco.com"
7 | login_url = '/api/fmc_platform/v1/auth/generatetoken'
8 | headers = {'Content-Type': 'application/json'}
9 |
10 | user = 'knox'
11 | pw = 'BtNdJM9k'
12 |
13 | try:
14 | # POST the login ans password to the login endpoint
15 | login_response = requests.post(
16 | f'{url}{login_url}', auth=(user, pw), verify=False)
17 |
18 | # Parse out the headers
19 | resp_headers = login_response.headers
20 |
21 | # Grab the token from the response headers
22 | token = resp_headers.get('X-auth-access-token', default=None)
23 | if token == None:
24 | print('Failed to get a token. Try again')
25 | sys.exit()
26 |
27 | # Set the token in the headers to be used in the next call
28 | headers['X-auth-access-token'] = token
29 | except Exception as err:
30 | print(f"error raised! {err}")
31 |
32 | # Get monitored apps
33 | apps_url = '/api/fmc_config/v1/domain/e276abec-e0f2-11e3-8169-6d9ed49b625f/object/applications'
34 |
35 | try:
36 | apps_response = requests.get(
37 | f'{url}{apps_url}', headers=headers, verify=False).json()
38 |
39 | print(json.dumps(apps_response, indent=2, sort_keys=True))
40 | except Exception as err:
41 | print(f"error raised! {err}")
42 | finally:
43 | if apps_response:
44 | apps_response.close()
45 |
--------------------------------------------------------------------------------
/Python/Networking/UCS/ucs.py:
--------------------------------------------------------------------------------
1 | from ucsmsdk.ucshandle import UcsHandle
2 | handle = UcsHandle("10.10.20.113", "ucspe", "ucspe")
3 | handle.login()
4 | # DOCUMENTATION https://github.com/CiscoUcs/ucsmsdk https://ucsmsdk.readthedocs.io/en/latest/
5 | ######## ORG INFO ###########
6 | org = handle.query_classid(class_id="orgOrg", hierarchy=True)
7 | print(org)
8 |
9 | ########## Server Blade info ############
10 | servers = handle.query_classid("computeBlade")
11 | # print(srv)
12 | for server in servers:
13 | print(server)
14 |
15 | for server in servers:
16 | print(server.dn, server.num_of_cpus, server.available_memory)
17 |
18 | ####### Specific DN query ###############
19 | blade = handle.query_dn('sys/chassis-3/blade-1')
20 | print(blade)
21 | # Logout
22 | handle.logout()
23 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Welcome to Knoxs Code Samples
2 | I'm glad you're here
3 |
4 | More to come!
--------------------------------------------------------------------------------
/SQL/DP300/Backups/backup_filegroups.sql:
--------------------------------------------------------------------------------
1 | USE SWDB
2 | GO
3 |
4 | --Create SECONDARY filegroup
5 | --Add new files into the filegroup
6 |
7 | CREATE UNIQUE CLUSTERED INDEX PK_Planets
8 | ON dbo.Planets(PlanetID)
9 | WITH DROP_EXISTING
10 | ON SECONDARY
11 | GO
12 |
13 | CREATE UNIQUE CLUSTERED INDEX PK_People
14 | ON dbo.People(PersonID)
15 | WITH DROP_EXISTING
16 | ON SECONDARY
17 | GO
18 |
19 | BACKUP DATABASE SWDB
20 | FILEGROUP = 'SECONDARY'
21 | TO DISK = '\\file-nug\backups\SWDB_sec_fg.bak'
22 | GO
23 |
24 | BACKUP DATABASE SWDB
25 | FILEGROUP = 'SECONDARY'
26 | TO DISK = '\\file-nug\backups\SWDB_sec_fg_diff.bak'
27 | WITH DIFFERENTIAL
28 | GO
29 |
30 | BACKUP DATABASE SWDB
31 | FILE = 'SWDB_data'
32 | TO DISK = '\\file-nug\backups\SWDB_data_file1.bak'
33 | GO
--------------------------------------------------------------------------------
/SQL/DP300/Backups/restore_filegroups.sql:
--------------------------------------------------------------------------------
1 | USE master
2 | GO
3 |
4 | --tail log backup
5 | BACKUP LOG SWDB
6 | TO FILE = '\\file-nug\backups\swdb_tlog.bak'
7 | WITH NORECOVERY
8 | GO
9 |
10 | RESTORE DATABASE SWDB
11 | FILEGROUP='PRIMARY'
12 | FROM DISK = '\\file-nug\backups\SWDB_full.bak'
13 | WITH NORECOVERY, PARTIAL, REPLACE;
14 | GO
15 |
16 | RESTORE DATABASE SWDB
17 | FILEGROUP='PRIMARY'
18 | FROM DISK = '\\file-nug\backups\SWDB_diff.bak'
19 | WITH NORECOVERY;
20 | GO
21 |
22 | RESTORE DATABASE SWDB
23 | FILEGROUP='PRIMARY'
24 | FROM DISK = '\\file-nug\backups\SWDB_log.bak'
25 | WITH NORECOVERY;
26 | GO
27 |
28 | RESTORE DATABASE SWDB
29 | FILEGROUP='PRIMARY'
30 | FROM DISK = '\\file-nug\backups\SWDB_tlog.bak'
31 | WITH RECOVERY;
32 | GO
33 |
34 |
35 | RESTORE DATABASE SWDB
36 | FILEGROUP='SECONDARY'
37 | FROM DISK = '\\file-nug\backups\SWDB_full.bak'
38 | WITH NORECOVERY;
39 | GO
40 |
41 | RESTORE DATABASE SWDB
42 | FILEGROUP='SECONDARY'
43 | FROM DISK = '\\file-nug\backups\SWDB_diff.bak'
44 | WITH NORECOVERY;
45 | GO
46 |
47 | RESTORE DATABASE SWDB
48 | FILEGROUP='SECONDARY'
49 | FROM DISK = '\\file-nug\backups\SWDB_log.bak'
50 | WITH NORECOVERY;
51 | GO
52 |
53 | RESTORE DATABASE SWDB
54 | FILEGROUP='SECONDARY'
55 | FROM DISK = '\\file-nug\backups\SWDB_tlog.bak'
56 | WITH RECOVERY;
57 | GO
--------------------------------------------------------------------------------
/SQL/DP300/Backups/restore_pages.sql:
--------------------------------------------------------------------------------
1 |
2 | USE master
3 | GO
4 |
5 | DBCC IND(SWDB, 'dbo.People',1)
6 | GO
7 |
8 | ALTER DATABASE SWDB SET SINGLE_USER;
9 | GO
10 |
11 | DBCC WRITEPAGE('SWDB', 3, 8, 1, 1, 0x00, 1)
12 | GO
13 |
14 | ALTER DATABASE SWDB SET MULTI_USER;
15 | GO
16 |
17 | USE SWDB
18 | GO
19 |
20 | SELECT * FROM dbo.People
21 | SELECT * FROM msdb.dbo.suspect_pages
22 |
23 | USE master
24 | GO
25 |
26 | --tail log backup
27 | BACKUP LOG SWDB
28 | TO DISK = '\\file-nug\backups\swdb_tlog.bak'
29 | WITH NORECOVERY
30 | GO
31 |
32 |
33 | RESTORE DATABASE SWDB
34 | PAGE = '3:8'
35 | FROM DISK = '\\file-nug\backups\SWDB_full.bak'
36 | WITH NORECOVERY
37 | GO
38 |
39 | RESTORE DATABASE SWDB
40 | FROM DISK = '\\file-nug\backups\SWDB_diff.bak'
41 | WITH NORECOVERY
42 | GO
43 |
44 | RESTORE DATABASE SWDB
45 | FROM DISK = '\\file-nug\backups\SWDB_log.bak'
46 | WITH NORECOVERY
47 | GO
48 |
49 | RESTORE DATABASE SWDB
50 | FROM DISK = '\\file-nug\backups\swdb_tlog.bak'
51 | WITH RECOVERY
52 | GO
--------------------------------------------------------------------------------
/SQL/DP300/SampleData/createClinicsDB.sql:
--------------------------------------------------------------------------------
1 | CREATE TABLE [dbo].[Patients](
2 | [PatientID] int IDENTITY(1,1),
3 | [SSN] char(11) NOT NULL,
4 | [FirstName] nvarchar(50) NULL,
5 | [LastName] nvarchar(50) NULL,
6 | [MiddleName] nvarchar(50) NULL,
7 | [StreetAddress] nvarchar(50) NULL,
8 | [City] nvarchar(50) NULL,
9 | [ZipCode] char(5) NULL,
10 | [State] char(2) NULL,
11 | [BirthDate] date NOT NULL
12 | PRIMARY KEY CLUSTERED ([PatientID] ASC) ON [PRIMARY]);
13 | GO
--------------------------------------------------------------------------------
/SQL/DP300/SampleData/createNLDB.sql:
--------------------------------------------------------------------------------
1 | CREATE TABLE dbo.CreditCards(
2 | CreditCardID INT PRIMARY KEY CLUSTERED,
3 | CardNumber NVARCHAR(50) NOT NULL,
4 | CardLast4 INT NOT NULL,
5 | CardExpMonth TINYINT NOT NULL,
6 | CardExpYear SMALLINT NOT NULL
7 | );
8 | GO
9 |
10 | INSERT INTO dbo.CreditCards VALUES (1,'1111222233334444',4444,9,2022)
11 | INSERT INTO dbo.CreditCards VALUES (2,'2222333344445555',5555,3,2022)
12 | INSERT INTO dbo.CreditCards VALUES (3,'3333444455556666',6666,1,2022)
13 | INSERT INTO dbo.CreditCards VALUES (4,'4444555566667777',7777,10,2022)
14 | GO
15 |
16 | CREATE TABLE dbo.Employees(
17 | EmployeeID INT PRIMARY KEY CLUSTERED,
18 | FirstName NVARCHAR(50) NOT NULL,
19 | LastName NVARCHAR(50) NOT NULL,
20 | Salary BIGINT NOT NULL,
21 | SSNumber NVARCHAR(20) NULL
22 | );
23 | GO
24 |
25 | INSERT INTO dbo.Employees VALUES (1,'Darth','Vader',100000000,'111-22-3333')
26 | INSERT INTO dbo.Employees VALUES (2,'Luke','Skywalker',5000000,'222-33-4444')
27 | INSERT INTO dbo.Employees VALUES (3,'Leia','Skywalker',5000000,'333-44-5555')
28 | GO
29 |
30 | SELECT * FROM sys.column_master_keys
31 |
32 | SELECT * FROM sys.column_encryption_keys
33 |
--------------------------------------------------------------------------------
/SQL/DP300/alwaysenc/azkv.ps1:
--------------------------------------------------------------------------------
1 | $subscriptionName = 'Pay-As-You-Go'
2 | $userPrincipalName = 'knox@knoxsdata.com'
3 | $applicationId = ''
4 | $resourceGroupName = 'appdev' # use the same resource group name when creating your SQL Database below
5 | $location = 'southcentralus'
6 | $vaultName = 'knoxsqlencr'
7 |
8 | Connect-AzAccount
9 | $subscriptionId = (Get-AzSubscription -SubscriptionName $subscriptionName).Id
10 | Set-AzContext -SubscriptionId $subscriptionId
11 |
12 | New-AzResourceGroup -Name $resourceGroupName -Location $location
13 | New-AzKeyVault -VaultName $vaultName -ResourceGroupName $resourceGroupName -Location $location
14 |
15 | Set-AzKeyVaultAccessPolicy -VaultName $vaultName -ResourceGroupName $resourceGroupName -PermissionsToKeys create,get,wrapKey,unwrapKey,sign,verify,list -UserPrincipalName $userPrincipalName
16 | Set-AzKeyVaultAccessPolicy -VaultName $vaultName -ResourceGroupName $resourceGroupName -ServicePrincipalName $applicationId -PermissionsToKeys get,wrapKey,unwrapKey,sign,verify,list
--------------------------------------------------------------------------------
/SQL/DP300/authentication/auth.sql:
--------------------------------------------------------------------------------
1 | CREATE LOGIN [nuggetlab\dvader]
2 | FROM WINDOWS
3 | GO
4 |
5 | CREATE LOGIN [nuggetlab\DBAs]
6 | FROM WINDOWS
7 | GO
8 |
9 | CREATE LOGIN JrDev
10 | WITH PASSWORD = 'Str0ngP@55' MUST_CHANGE, CHECK_EXPIRATION=ON, CHECK_POLICY=ON
11 | GO
12 |
13 | CREATE LOGIN SrDev
14 | WITH PASSWORD = 'Str0ngP@55'
15 | GO
16 |
17 | USE NuggetlabDB
18 | GO
19 |
20 | --Normal Windows User
21 | CREATE USER DBAs
22 | FOR LOGIN [nuggetlab\DBAs]
23 | GO
24 |
25 | --Normal SQL User
26 | CREATE USER JrDev
27 | FOR LOGIN JrDev
28 | GO
29 | --Sproc User
30 | CREATE USER SprocUser
31 | WITHOUT LOGIN
32 | GO
33 | --Contained User
34 | CREATE USER [nuggetlab\knox]
35 |
36 | CREATE USER ContainedUser
37 | WITH PASSWORD = 'Str0ngP@55'
38 | GO
39 |
--------------------------------------------------------------------------------
/SQL/DP300/authorization/db.sql:
--------------------------------------------------------------------------------
1 | USE nuggetlabDB
2 | GO
3 |
4 | CREATE ROLE devTeam AUTHORIZATION db_securityadmin;
5 | GO
6 |
7 | ALTER ROLE devTeam
8 | ADD MEMBER [nuggetlan\DBAs]
9 | GO
10 | GRANT CREATE TABLE TO devTeam
11 | GRANT CREATE PROCEDURE TO devTeam
12 | GRANT CREATE FUNCTION TO devTeam
13 | GRANT CREATE TYPE TO devTeam
14 | GRANT EXECUTE TO devTeam
15 | GO
--------------------------------------------------------------------------------
/SQL/DP300/authorization/server.sql:
--------------------------------------------------------------------------------
1 | USE master
2 | GO
3 |
4 | CREATE SERVER ROLE ServerTeam
5 | GO
6 | ALTER Server ROLE ServerTeam
7 | ADD MEMBER [nuggetlab\Administrator]
8 | GO
9 |
10 | GRANT CONNECT SQL TO ServerTeam
11 | GRANT VIEW ANY DATABASE TO ServerTeam
12 | GRANT VIEW SERVER STATE TO ServerTeam
13 | GRANT ALTER SERVER STATE TO ServerTeam
14 | GRANT ALTER SETTINGS TO ServerTeam
15 | GRANT SHUTDOWN TO ServerTeam
16 | GO
--------------------------------------------------------------------------------
/SQL/DP300/authorization/tier.sql:
--------------------------------------------------------------------------------
1 | CREATE SCHEMA Sales
2 | GO
3 |
4 | CREATE TABLE [sales].[Customers](
5 | CustomerID INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
6 | FirstName varchar(100),
7 | LastName varchar(100),
8 | CreateDate DATETIME DEFAULT GETDATE()
9 | )
10 |
11 | CREATE TABLE [sales].[sales](
12 | SaleID INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
13 | SaleDate DATETIME DEFAULT GETDATE(),
14 | ProductName varchar(100),
15 | ProductDescription varchar(200)
16 | )
17 |
18 | GRANT SELECT ON SCHEMA::Sales TO devTeam
19 | GRANT INSERT ON SCHEMA::Sales TO devTeam
20 | GRANT UPDATE ON SCHEMA::Sales TO devTeam
21 | GRANT DELETE ON SCHEMA::Sales TO devTeam
22 |
23 | --Revoking
24 | REVOKE UPDATE ON SCHEMA::Sales to devTeam
25 | REVOKE DELETE ON SCHEMA::Sales TO devTeam
26 | USE master
27 | GO
28 | CREATE LOGIN [nuggetlab\luskywalker]
29 | FROM WINDOWS
30 | USE NuggetlabDB
31 | GO
32 | CREATE USER luskywalker
33 | FOR LOGIN [nuggetlab\luskywalker]
34 | GO
35 | GRANT DELETE ON SCHEMA::Sales to devTeam
36 |
37 | --Deny
38 | DENY DELETE ON Sales.Customers to devTeam
39 |
40 | --column level
41 | GRANT SELECT on Sales.sales([SaleID],ProductName) TO devTeam
--------------------------------------------------------------------------------
/SQL/DP300/encAtRest/TDE.sql:
--------------------------------------------------------------------------------
1 | USE master;
2 | GO
3 |
4 | --Database Master Key
5 | CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'myP@%5w0rd';
6 | GO
7 |
8 | CREATE CERTIFICATE SqlNug1Cert
9 | WITH SUBJECT = 'TDE Cert'
10 | GO
11 |
12 | USE NuggetlabDB
13 | GO
14 | --Database Encryption Key
15 | CREATE DATABASE ENCRYPTION KEY WITH ALGORITHM = AES_256 ENCRYPTION BY SERVER CERTIFICATE SqlNug1Cert
16 | GO
17 |
18 | ALTER DATABASE NuggetlabDB
19 | SET ENCRYPTION ON
20 | GO
21 |
22 | --BACKUP OPERATIONS
23 | USE master;
24 | GO
25 |
26 | BACKUP SERVICE MASTER KEY
27 | TO FILE = 'C:\SQLNUG.smk'
28 | ENCRYPTION BY PASSWORD = 'SMKmyP@%5w0rd'
29 | GO
30 |
31 |
32 | BACKUP MASTER KEY
33 | TO FILE = 'C:\DBMK.dmk'
34 | ENCRYPTION BY PASSWORD = 'DMKmyP@%5w0rd'
35 | GO
36 |
37 | BACKUP CERTIFICATE SqlNug1Cert
38 | TO FILE = 'C:\CertDEK.dek'
39 | WITH PRIVATE KEY (
40 | FILE = 'C:\DEKkey.key',
41 | ENCRYPTION BY PASSWORD = 'CERTmyP@%5w0rd'
42 | )
43 |
44 |
45 | --RESTORE
46 | CREATE CERTIFICATE SqlNug1Cert
47 | FROM FILE = 'C:\CertDEK.dek'
48 | WITH PRIVATE KEY (
49 | FILE = 'C:\DEKkey.key',
50 | DECRYPTION BY PASSWORD = 'CERTmyP@%5w0rd'
51 | )
--------------------------------------------------------------------------------
/SQL/DP300/encAtRest/diskenc.ps1:
--------------------------------------------------------------------------------
1 | $VMName = 'sqlknoxvm'
2 | $ResourceGroupName = 'appdev'
3 | $KeyVaultName = 'knoxsqlkv'
4 | $location = 'southcentralus'
5 |
6 | New-AzKeyVault -Name $KeyVaultName `
7 | -ResourceGroupName $ResourceGroupName `
8 | -location $location `
9 | -EnabledForDiskEncryption
10 |
11 | $vault = Get-AzKeyVault -VaultName $KeyVaultName -ResourceGroupName $ResourceGroupName
12 |
13 | Set-AzVmDiskEncryptionExtension -ResourceGroupName $ResourceGroupName `
14 | -VMName $VMName `
15 | -DiskEncryptionKeyVaultId $vault.ResourceId `
16 | -DiskEncryptionKeyVaultUrl $vault.VaultUri `
17 | -SkipVmBackup `
18 | -VolumeType All
19 |
20 | Get-AzVmDiskEncryptionStatus -ResourceGroupName $ResourceGroupName -VMName $VMName
21 |
22 | ### USE AN OPTIONAL KEK ###
23 | Add-AzKeyVaultKey -VaultName $KeyVaultName `
24 | -Name "MyKek" `
25 | -Destination "HSM" `
26 | -Size 2048
27 |
28 | Set-AzVmDiskEncryptionExtension -ResourceGroupName $ResourceGroupName `
29 | -VMName $VMName `
30 | -DiskEncryptionKeyVaultId $vault.ResourceId `
31 | -DiskEncryptionKeyVaultUrl $vault.VaultUri `
32 | -KeyEncryptionKeyVaultId $vault.ResourceId `
33 | -KeyEncryptionKeyVaultUrl $vault.VaultUri `
34 | -KeyEncryptionKeyUrl $vault.VaultUri + "/keys/MyKek" `
35 | -SkipVmBackup `
36 | -VolumeType All
37 |
--------------------------------------------------------------------------------
/SQL/DP300/identify query issue/querystore.sql:
--------------------------------------------------------------------------------
1 | USE NugDB
2 | GO
3 |
4 | ALTER DATABASE NugDB
5 | SET QUERY_STORE = ON
6 |
7 | ALTER DATABASE NugDB
8 | SET QUERY_STORE (
9 | OPERATION_MODE = READ_WRITE,
10 | CLEANUP_POLICY = (STALE_QUERY_THRESHOLD_DAYS = 15),
11 | DATA_FLUSH_INTERVAL_SECONDS = 1500,
12 | MAX_STORAGE_SIZE_MB = 250,
13 | INTERVAL_LENGTH_MINUTES = 10,
14 | SIZE_BASED_CLEANUP_MODE = AUTO,
15 | QUERY_CAPTURE_MODE = AUTO,
16 | MAX_PLANS_PER_QUERY = 200);
17 |
18 | SELECT * FROM sys.database_query_store_options
19 |
20 | ALTER DATABASE NugDB
21 | SET QUERY_STORE CLEAR ALL;
22 |
23 |
24 | use WideWorldImporters
25 | GO
26 |
27 | CREATE PROCEDURE GetSalesByCustomer(
28 | @CustomerId INT
29 | )
30 | AS
31 | Select Customerid, SalespersonPersonId, BackorderOrderId, OrderDate
32 | FROM Sales.Orders
33 | WHERE CustomerId = @CustomerId
34 | Group By CustomerID
35 | GO
36 |
37 | EXEC GetSalesByCustomer 205;
38 | GO 10
39 |
40 | CREATE NONCLUSTERED INDEX NCIX_CustomerSales
41 | ON sales.Orders(CustomerId,SalespersonPersonID,BackorderOrderId,OrderDate)
--------------------------------------------------------------------------------
/SQL/DP300/index/fragment_cstore.sql:
--------------------------------------------------------------------------------
1 | SELECT *
2 | FROM sys.dm_db_column_store_row_group_physical_stats;
3 |
4 | SELECT *
5 | FROM sys.dm_db_column_store_row_group_operational_stats;
6 |
7 |
8 | DECLARE @cnt INT;
9 | DECLARE @OrderId INT;
10 | DECLARE @ItemID INT;
11 | DECLARE @OrderDesc NVARCHAR(100);
12 | DECLARE @PackageTypeID INT;
13 | DECLARE @Quantity INT;
14 |
15 | SELECT @cnt = 0;
16 | WHILE (@cnt<10000)
17 | BEGIN
18 | SET @OrderID = CAST(RAND()*70000 AS INT)+1;
19 | SET @ItemID = CAST(RAND() * 225 AS INT)+1;
20 | SET @OrderDesc = 'Desc: '+ CONVERT(NVARCHAR(255),@OrderID);
21 | SET @PackageTypeID = CAST(RAND()*5 AS INT)+1;
22 | SET @Quantity = CAST(RAND()*50 AS INT)+1;
23 |
24 | INSERT INTO Sales.OrderLines WITH (TABLOCK) (OrderId,StockItemID,Description,PackageTypeID,Quantity,TaxRate,PickedQuantity,LastEditedBy,LastEditedWhen)
25 | VALUES (@OrderId,@ItemID,@OrderDesc,@PackageTypeID,@Quantity,15,@Quantity,1,GETDATE())
26 | SELECT @cnt=@cnt+1;
27 | END
28 | GO;
29 |
30 |
31 | SELECT *
32 | FROM dm.sys_db_column_store_row_group_physical_stats
33 | WHERE object_id = object_id('Sales.OrderLines');
34 | GO
35 |
36 | ALTER INDEX NCCX_Sales_OrderLines ON Sales.OrderLines
37 | REORGANIZE WITH (COMPRESS_ALL_ROW_GROUPS = ON);
38 | GO
39 |
40 | ALTER INDEX NCCX_Sales_OrderLines ON Sales.OrderLines
41 | REBUILD WITH (DATA_COMPRESSION = COLUMNSTORE_ARCHIVE);
42 | GO
43 |
--------------------------------------------------------------------------------
/SQL/DP300/index/missing.sql:
--------------------------------------------------------------------------------
1 | USE AdventureWorks2019;
2 | GO
3 |
4 | SELECT [Name], ModifiedDate
5 | FROM Sales.Store
6 | WHERE [Name] = 'Twin Cycles'
7 |
8 | SELECT [Name], ModifiedDate
9 | FROM Sales.Store
10 | WHERE [Name] = 'Twin Cycles' AND ModifiedDate > '01/01/2010'
11 |
12 | SELECT *
13 | FROM sys.dm_db_missing_index_details
14 |
15 | SELECT *
16 | FROM sys.dm_db_missing_index_groups
17 |
18 | SELECT *
19 | FROM sys.dm_db_missing_index_group_stats
20 |
21 |
22 | SELECT DISTINCT
23 | OBJECT_NAME(mid.object_id) as TableName,
24 | mid.equality_columns,
25 | mid.inequality_columns,
26 | mid.included_columns,
27 | migs.unique_compiles,
28 | migs.user_seeks,
29 | migs.last_user_seek,
30 | migs.avg_total_user_cost,
31 | migs.avg_user_impact
32 | FROM sys.dm_db_missing_index_group_stats as migs
33 | JOIN sys.dm_db_missing_index_groups as mig ON migs.group_handle = mig.index_group_handle
34 | JOIN sys.dm_db_missing_index_details as mid ON mig.index_handle = mid.index_handle
35 | WHERE mid.database_id = DB_ID();
--------------------------------------------------------------------------------
/SQL/DP300/index/utilization.sql:
--------------------------------------------------------------------------------
1 | USE AdventureWorks2019;
2 | GO
3 |
4 | --operational stats
5 | SELECT *
6 | FROM sys.dm_db_index_operational_stats(DB_ID(),NULL,NULL,NULL)
7 | --usage stats with indexes
8 | --look for write activity like updates but low read activity
9 | SELECT
10 | OBJECT_NAME(ius.object_id) as TableName,
11 | i.name as IndexName,
12 | user_seeks,
13 | user_scans,
14 | user_lookups,
15 | user_updates
16 | FROM sys.dm_db_index_usage_stats ius
17 | JOIN sys.indexes i on i.object_id = ius.object_id AND i.index_id=ius.index_id;
18 |
19 |
20 | --big time
21 | SELECT
22 | 'DROP INDEX' + OBJECT_NAME(ius.object_id)+'.'+i.name AS DropStatement,
23 | user_seeks,
24 | user_scans,
25 | user_lookups,
26 | user_updates
27 | FROM sys.dm_db_index_usage_stats ius
28 | JOIN sys.objects o ON ius.object_id=o.object_id
29 | JOIN sys.indexes i on i.index_id = ius.index_id AND ius.object_id = i.object_id
30 | WHERE
31 | i.is_primary_key = 0 AND
32 | i.is_unique = 0 AND
33 | ius.user_updates<>0 AND
34 | ius.user_lookups = 0 AND
35 | ius.user_seeks = 0 AND
36 | ius.user_scans = 0
37 | ORDER BY ius.user_updates DESC
38 |
--------------------------------------------------------------------------------
/SQL/DP500/Adv Data Sources/demo.pbix:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DataKnox/CodeSamples/8b375eedfca5b9e5d8965cfedbb073dddcaac091/SQL/DP500/Adv Data Sources/demo.pbix
--------------------------------------------------------------------------------
/SQL/DP500/Adv Data Sources/ml_rpt.pbix:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DataKnox/CodeSamples/8b375eedfca5b9e5d8965cfedbb073dddcaac091/SQL/DP500/Adv Data Sources/ml_rpt.pbix
--------------------------------------------------------------------------------
/SQL/DP500/Adv Data Sources/yellow_tripdata_2022-04.parquet:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DataKnox/CodeSamples/8b375eedfca5b9e5d8965cfedbb073dddcaac091/SQL/DP500/Adv Data Sources/yellow_tripdata_2022-04.parquet
--------------------------------------------------------------------------------
/SQL/DP500/PREDICT/build.py:
--------------------------------------------------------------------------------
1 | # pip3 install scikit-learn numpy onnxmltools onnxruntime pyodbc setuptools skl2onnx sqlalchemy pandas
2 |
3 |
4 | import pandas as pd # doctest: +SKIP
5 | import numpy as np
6 | import pyodbc
7 |
8 | from sklearn.datasets import fetch_california_housing
9 | housing = fetch_california_housing()
10 | print(housing)
11 |
12 |
13 | drivers = pyodbc.drivers()
14 | print(drivers)
15 |
--------------------------------------------------------------------------------
/SQL/DP500/PREDICT/cali1.model.onnx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DataKnox/CodeSamples/8b375eedfca5b9e5d8965cfedbb073dddcaac091/SQL/DP500/PREDICT/cali1.model.onnx
--------------------------------------------------------------------------------
/SQL/DP500/Pwsh Monitor/pwsh.ps1:
--------------------------------------------------------------------------------
1 | # POWER BI POWERSHELL DOCS https://docs.microsoft.com/en-us/powershell/power-bi/overview?view=powerbi-ps
2 | #=
3 | Install-Module -Name MicrosoftPowerBIMgmt -Scope CurrentUser
4 |
5 | Login-PowerBI
6 |
7 | Get-Command -Module MicrosoftPowerBIMgmt*
8 | get-help Get-PowerBIGroup
9 | # Current user's workspaces
10 | Get-PowerBIWorkspace
11 | Get-PowerBIWorkspace -Name Dev
12 |
13 | # All workspaces, admin
14 | Get-PowerBIWorkspace -Scope Organization
15 |
16 | Get-PowerBIReport
17 | Get-PowerBIDataset
18 |
19 | # EXPLORE REST API AUTHENTICATION WITH POWERSHELL
20 | # https://github.com/Azure-Samples/powerbi-powershell/blob/master/manageRefresh.ps1
--------------------------------------------------------------------------------
/SQL/DP500/Query DW/bigger sum.sql:
--------------------------------------------------------------------------------
1 | SELECT dates.CalendarYear,
2 | dates.CalendarQuarter,
3 | custs.BirthDate,
4 | SUM(sales.SalesAmount) AS TotalSales
5 | FROM dbo.FactInternetSales AS sales
6 | JOIN dbo.DimDate AS dates ON sales.OrderDateKey = dates.DateKey
7 | JOIN dbo.DimCustomer AS custs ON sales.CustomerKey = custs.CustomerKey
8 | GROUP BY dates.CalendarYear, dates.CalendarQuarter, custs.BirthDate
9 | ORDER BY dates.CalendarYear, dates.CalendarQuarter, custs.BirthDate;
--------------------------------------------------------------------------------
/SQL/DP500/Query DW/rank.sql:
--------------------------------------------------------------------------------
1 | SELECT ProductSubCategoryKey,
2 | EnglishProductName,
3 | ListPrice,
4 | ROW_NUMBER() OVER
5 | (PARTITION BY ProductSubCategoryKey ORDER BY ListPrice DESC) AS RowNumber,
6 | RANK() OVER
7 | (PARTITION BY ProductSubCategoryKey ORDER BY ListPrice DESC) AS Rank,
8 | DENSE_RANK() OVER
9 | (PARTITION BY ProductSubCategoryKey ORDER BY ListPrice DESC) AS DenseRank,
10 | NTILE(4) OVER
11 | (PARTITION BY ProductSubCategoryKey ORDER BY ListPrice DESC) AS Quartile
12 | FROM dbo.DimProduct
13 | ORDER BY ProductSubCategoryKey;
14 |
15 |
16 | SELECT cat.EnglishProductSubCategoryName,
17 | SUM(sales.OrderQuantity) AS ItemsSold,
18 | RANK() OVER
19 | (ORDER BY SUM(sales.OrderQuantity)) as Rank
20 | FROM dbo.FactInternetSales AS sales
21 | JOIN dbo.DimProduct AS prod ON sales.ProductKey = prod.ProductKey
22 | JOIN dbo.DimProductSubCategory AS cat ON prod.ProductSubCategoryKey = cat.ProductSubCategoryKey
23 | GROUP BY cat.EnglishProductSubCategoryName
24 | ORDER BY SUM(sales.OrderQuantity);
--------------------------------------------------------------------------------
/SQL/DP500/Query DW/snowflake.sql:
--------------------------------------------------------------------------------
1 | SELECT cat.EnglishProductSubCategoryName,
2 | SUM(sales.OrderQuantity) AS ItemsSold
3 | FROM dbo.FactInternetSales AS sales
4 | JOIN dbo.DimProduct AS prod ON sales.ProductKey = prod.ProductKey
5 | JOIN dbo.DimProductSubCategory AS cat ON prod.ProductSubCategoryKey = cat.ProductSubCategoryKey
6 | GROUP BY cat.EnglishProductSubCategoryName
7 | ORDER BY cat.EnglishProductSubCategoryName;
--------------------------------------------------------------------------------
/SQL/DP500/Query DW/sum.sql:
--------------------------------------------------------------------------------
1 | SELECT dates.CalendarYear,
2 | dates.CalendarQuarter,
3 | SUM(sales.SalesAmount) AS TotalSales
4 | FROM dbo.FactInternetSales AS sales
5 | JOIN dbo.DimDate AS dates ON sales.OrderDateKey = dates.DateKey
6 | GROUP BY dates.CalendarYear, dates.CalendarQuarter
7 | ORDER BY dates.CalendarYear, dates.CalendarQuarter;
--------------------------------------------------------------------------------
/SQL/DP500/Query Synapse/product1.json:
--------------------------------------------------------------------------------
1 | {
2 | "product_id": 100,
3 | "product_name": "Doodad",
4 | "list_price": 11.55
5 | }
--------------------------------------------------------------------------------
/SQL/DP500/Query Synapse/product2.json:
--------------------------------------------------------------------------------
1 | {
2 | "product_id": 101,
3 | "product_name": "Gizmo",
4 | "list_price": 11.55
5 | }
--------------------------------------------------------------------------------
/SQL/DP500/sourcecontrol/DevOpsProd-basedata.khutc.tmuo:
--------------------------------------------------------------------------------
1 | {
2 | "Deployment": {
3 | "TargetConnectionString": "powerbi://api.powerbi.com/v1.0/myorg/DevOpsProd",
4 | "TargetDatabase": "basedata-bak",
5 | "TargetCredentials": {
6 | "EncryptedPassword": "AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAArxF7fQT/QkiIuhPDpxN3/gAAAAACAAAAAAAQZgAAAAEAACAAAACuhi3WS2fKzOSkSI0vPJiCNk/8ZE4QpHVDsj2X09JhPAAAAAAOgAAAAAIAACAAAACn+Y/GzlBh+9kr/vPswWkucEChazamZT5gbMzxgWsc7iAAAAAawLznTN0ZOWQYoDyOy4hwALkcU4xmQDwfIjQ8rPgS60AAAAAKnX0MGqHeboRjbxW+/u3R0aOepmJLNPN6goRWOlOwUlQa/5Szrn65C34nkNrnwyGJlNU8OVLIKEFheuARbxKd",
7 | "UserName": "knox@knoxsdata.com"
8 | },
9 | "DeployDataSources": true,
10 | "DeployPartitions": true,
11 | "DeployRefreshPolicyPartitions": true,
12 | "DeployModelRoles": false,
13 | "DeployModelRoleMembers": false
14 | }
15 | }
--------------------------------------------------------------------------------
/SQL/DP500/sourcecontrol/OLS.pbix:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DataKnox/CodeSamples/8b375eedfca5b9e5d8965cfedbb073dddcaac091/SQL/DP500/sourcecontrol/OLS.pbix
--------------------------------------------------------------------------------
/SQL/DP500/sourcecontrol/basedata.pbix:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DataKnox/CodeSamples/8b375eedfca5b9e5d8965cfedbb073dddcaac091/SQL/DP500/sourcecontrol/basedata.pbix
--------------------------------------------------------------------------------
/SQL/DP500/sourcecontrol/basedatamodel.khutc.tmuo:
--------------------------------------------------------------------------------
1 | {
2 | "Deployment": {
3 | "TargetConnectionString": "powerbi://api.powerbi.com/v1.0/myorg/DevOpsProd",
4 | "TargetDatabase": "demo1",
5 | "TargetCredentials": {
6 | "EncryptedPassword": "AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAArxF7fQT/QkiIuhPDpxN3/gAAAAACAAAAAAAQZgAAAAEAACAAAAAZkIh+T9MMwUqx+yrNg9fHebJ31KGfOuzH4R9j1Tp9sQAAAAAOgAAAAAIAACAAAADiduHobs8iytGzPwa7cd3j4481fuY0r6USgNBi0+x9dCAAAADVmLVCbrTvnv7oyYt27tDUiSra/levVcNFrAlPQJ/ZpEAAAADeTig2OOdGtrF4Zj0xxOzqyqycxarzIqDi7/Xgz/PQDz9ZEwVGHSsXMqvLEg0AmPwmZCyNTEP1FXJSmIPIUKaa",
7 | "UserName": "knox@knoxsdata.com"
8 | },
9 | "DeployDataSources": true,
10 | "DeployPartitions": true,
11 | "DeployRefreshPolicyPartitions": true,
12 | "DeployModelRoles": false,
13 | "DeployModelRoleMembers": false
14 | }
15 | }
--------------------------------------------------------------------------------
/SQL/DP500/sourcecontrol/calcgrps.pbix:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DataKnox/CodeSamples/8b375eedfca5b9e5d8965cfedbb073dddcaac091/SQL/DP500/sourcecontrol/calcgrps.pbix
--------------------------------------------------------------------------------
/SQL/DP500/sourcecontrol/demo.sql:
--------------------------------------------------------------------------------
1 | SELECT *
2 | FROM dbo.myTable
3 | WHERE column = 1
--------------------------------------------------------------------------------
/SQL/DP500/sourcecontrol/drls.pbix:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DataKnox/CodeSamples/8b375eedfca5b9e5d8965cfedbb073dddcaac091/SQL/DP500/sourcecontrol/drls.pbix
--------------------------------------------------------------------------------
/SQL/DP500/sourcecontrol/functions.pbix:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DataKnox/CodeSamples/8b375eedfca5b9e5d8965cfedbb073dddcaac091/SQL/DP500/sourcecontrol/functions.pbix
--------------------------------------------------------------------------------
/SQL/DP500/sourcecontrol/rls.pbix:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DataKnox/CodeSamples/8b375eedfca5b9e5d8965cfedbb073dddcaac091/SQL/DP500/sourcecontrol/rls.pbix
--------------------------------------------------------------------------------
/SQL/DP500/sourcecontrol/sampledatafoodsales.xlsx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DataKnox/CodeSamples/8b375eedfca5b9e5d8965cfedbb073dddcaac091/SQL/DP500/sourcecontrol/sampledatafoodsales.xlsx
--------------------------------------------------------------------------------
/SQL/DP500/sourcecontrol/sqlrls.pbix:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DataKnox/CodeSamples/8b375eedfca5b9e5d8965cfedbb073dddcaac091/SQL/DP500/sourcecontrol/sqlrls.pbix
--------------------------------------------------------------------------------
/SQL/DP500/spark query/basic_query.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": null,
6 | "metadata": {},
7 | "outputs": [],
8 | "source": [
9 | "%%pyspark\n",
10 | "df = spark.read.load('abfss://etlload@knoxlakegen2.dfs.core.windows.net/sales/SalesOrderDetail.csv',\n",
11 | "format='csv',\n",
12 | "header=True\n",
13 | ")\n",
14 | "display(df.limit(10))"
15 | ]
16 | }
17 | ],
18 | "metadata": {
19 | "kernelspec": {
20 | "display_name": "Python 3.9.7 64-bit",
21 | "language": "python",
22 | "name": "python3"
23 | },
24 | "language_info": {
25 | "name": "python",
26 | "version": "3.9.7"
27 | },
28 | "orig_nbformat": 4,
29 | "vscode": {
30 | "interpreter": {
31 | "hash": "0866b0178eadfcb04b475af301c22703d9d67512be1b7043443a666c4451acde"
32 | }
33 | }
34 | },
35 | "nbformat": 4,
36 | "nbformat_minor": 2
37 | }
38 |
--------------------------------------------------------------------------------
/env.py:
--------------------------------------------------------------------------------
1 | import os
2 | from dotenv import load_dotenv
3 | load_dotenv()
4 | user = os.environ.get('SWITCHUSER')
5 | print(user)
6 |
7 | new_user = os.environ.get('CISCOUSER')
8 | print(new_user)
9 |
--------------------------------------------------------------------------------
/sqlscript/ExternalSrcs.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ExternalSrcs",
3 | "properties": {
4 | "content": {
5 | "query": "--First create the DB\nCREATE DATABASE CurrencyDB\n COLLATE Latin1_General_100_BIN2_UTF8\n\n--Then link the data source\nCREATE EXTERNAL DATA SOURCE etlload\nWITH (\n LOCATION = 'https://dataknox.blob.core.windows.net/etlload'\n)\n\n-- SELECT *\n-- FROM\n-- OPENROWSET(\n-- BULK 'currency.csv',\n-- DATA_SOURCE = 'etlload',\n-- FORMAT = 'csv',\n-- PARSER_VERSION = '2.0',\n-- HEADER_ROW = TRUE\n-- ) AS currency\n\n-- Now define the formatting\nCREATE EXTERNAL FILE FORMAT CsvFormat\n WITH (\n FORMAT_TYPE = DELIMITEDTEXT,\n FORMAT_OPTIONS(\n FIELD_TERMINATOR = ',',\n STRING_DELIMITER = '\"'\n )\n );\nGO\n\n--Now create the table\nCREATE EXTERNAL TABLE dbo.currency\n(\n Code VARCHAR(6),\n Symbol VARCHAR(20),\n [Name] VARCHAR(38)\n)\nWITH\n(\n DATA_SOURCE = etlload,\n LOCATION = 'currency.csv',\n FILE_FORMAT = CsvFormat\n);\nGO\n\n-- query the table\nSELECT * FROM dbo.currency;",
6 | "metadata": {
7 | "language": "sql"
8 | },
9 | "currentConnection": {
10 | "databaseName": "CurrencyDB",
11 | "poolName": "Built-in"
12 | },
13 | "resultLimit": 5000
14 | },
15 | "type": "SqlQuery"
16 | }
17 | }
--------------------------------------------------------------------------------
/sqlscript/Filepath.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "Filepath",
3 | "properties": {
4 | "content": {
5 | "query": "SELECT ORDERDATE, STATUS, PRODUCTLINE, PRODUCTCODE, CUSTOMERNAME, DEALSIZE\nFROM OPENROWSET(\n BULK 'https://knoxlakegen2.blob.core.windows.net/etlload/archive/*/*/*.csv',\n FORMAT = 'csv',\n PARSER_VERSION = '2.0',\n HEADER_ROW = TRUE) AS orders\nWHERE orders.filepath(1) = '2005'\n AND orders.filepath(2) IN ('1')\n AND ORDERDATE IS NOT NULL;",
6 | "metadata": {
7 | "language": "sql"
8 | },
9 | "currentConnection": {
10 | "databaseName": "SQLPool01",
11 | "poolName": "Built-in"
12 | },
13 | "resultLimit": 5000
14 | },
15 | "type": "SqlQuery"
16 | }
17 | }
--------------------------------------------------------------------------------
/sqlscript/Qry_JSON_columns.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "Qry_JSON_columns",
3 | "properties": {
4 | "content": {
5 | "query": "SELECT JSON_VALUE(doc, '$.product_name') AS product,\n JSON_VALUE(doc, '$.list_price') AS price,\n JSON_VALUE(doc, '$.product_id') as ID\nFROM\n OPENROWSET(\n BULK 'https://knoxlakegen2.blob.core.windows.net/etlload/*.json',\n FORMAT = 'csv',\n FIELDTERMINATOR ='0x0b',\n FIELDQUOTE = '0x0b',\n ROWTERMINATOR = '0x0b'\n ) WITH (doc NVARCHAR(MAX)) as rows",
6 | "metadata": {
7 | "language": "sql"
8 | },
9 | "currentConnection": {
10 | "databaseName": "master",
11 | "poolName": "Built-in"
12 | },
13 | "resultLimit": 5000
14 | },
15 | "type": "SqlQuery"
16 | }
17 | }
--------------------------------------------------------------------------------
/sqlscript/Query_JSON.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "Query_JSON",
3 | "properties": {
4 | "content": {
5 | "query": "SELECT doc\nFROM\n OPENROWSET(\n BULK 'https://knoxlakegen2.blob.core.windows.net/etlload/*.json',\n FORMAT = 'csv',\n FIELDTERMINATOR ='0x0b',\n FIELDQUOTE = '0x0b',\n ROWTERMINATOR = '0x0b'\n ) WITH (doc NVARCHAR(MAX)) as rows",
6 | "metadata": {
7 | "language": "sql"
8 | },
9 | "currentConnection": {
10 | "databaseName": "master",
11 | "poolName": "Built-in"
12 | },
13 | "resultLimit": 5000
14 | },
15 | "type": "SqlQuery"
16 | }
17 | }
--------------------------------------------------------------------------------
/sqlscript/Serverless-Curr-Defined.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "Serverless-Curr-Defined",
3 | "properties": {
4 | "content": {
5 | "query": "SELECT TOP 100 *\nFROM OPENROWSET(\n BULK 'https://knoxlakegen2.blob.core.windows.net/etlload/curr*.*',\n FORMAT = 'csv')\nWITH (\n Code VARCHAR(10),\n Symbol VARCHAR(50),\n Name VARCHAR(100)\n) AS rows\n",
6 | "metadata": {
7 | "language": "sql"
8 | },
9 | "currentConnection": {
10 | "databaseName": "master",
11 | "poolName": "Built-in"
12 | },
13 | "resultLimit": 5000
14 | },
15 | "type": "SqlQuery"
16 | }
17 | }
--------------------------------------------------------------------------------
/sqlscript/Serverless-Currency-Infer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "Serverless-Currency-Infer",
3 | "properties": {
4 | "content": {
5 | "query": "SELECT TOP 100 *\nFROM OPENROWSET(\n BULK 'https://knoxlakegen2.blob.core.windows.net/etlload/currency.csv',\n FORMAT = 'csv',\n PARSER_VERSION = '2.0',\n HEADER_ROW = TRUE) AS rows",
6 | "metadata": {
7 | "language": "sql"
8 | },
9 | "currentConnection": {
10 | "databaseName": "master",
11 | "poolName": "Built-in"
12 | },
13 | "resultLimit": 5000
14 | },
15 | "type": "SqlQuery"
16 | }
17 | }
--------------------------------------------------------------------------------