返回文章列表

Python 網路自動化入門

本文介紹網路自動化的基礎概念,包含 Python 程式碼範例,涵蓋憑證安全處理、API 互動、正規表示式運用、檔案讀寫,以及 Git 版本控制。文章同時探討 PowerShell 在 Windows 環境下的優勢,並提供 PowerShell 程式設計例項,示範 API

網路自動化 Python

網路自動化是提升效率的關鍵,本文將介紹其核心概念,並以 Python 程式碼示範如何安全地處理憑證資訊、與 API 互動、運用正規表示式、讀寫檔案,以及使用 Git 進行版本控制。同時,我們也會探討 PowerShell 在 Windows 環境下的優勢,並提供相關程式碼範例,說明如何在 PowerShell 中呼叫 API 和與本地機器互動。最後,我們將以一個旅行社的應用案例,整合前面提到的技術,展示網路自動化的實際應用。

網路自動化基礎概念 第一章

隱藏憑證資訊

在網路自動化中,處理敏感資訊(如使用者名稱和密碼)時,必須小心避免將這些資訊以明文形式儲存在指令碼中。以下是一個使用Python處理憑證資訊的範例:

import getpass
import base64

def encryptcredential(creds):
    return base64.b64encode(creds.encode())

def decryptcredential(encryptedcreds):
    return base64.b64decode(encryptedcreds).decode()

creds = input("Enter your username :") + "*.*" + getpass.getpass()
encryptedcreds = encryptcredential(creds)
print("Simple creds: " + creds)
print("Encrypted creds: " + str(encryptedcreds))
print("Decrypted creds: " + decryptcredential(encryptedcreds))

內容解密:

  1. 輸入使用者名稱和密碼:使用input函式輸入使用者名稱,getpass.getpass隱藏輸入密碼。
  2. 加密憑證:將使用者名稱和密碼結合成一個字串,使用base64.b64encode進行編碼加密。
  3. 解密憑證:使用base64.b64decode將編碼後的字串解碼回原始憑證。
  4. 列印結果:列印原始憑證、加密後的憑證和解密後的憑證。

存取API

使用API(應用程式介面)是網路自動化中的一個重要概念。以下是一個使用Python存取OpenWeatherMap API的範例:

import requests

city = "london"
urlx = "https://samples.openweathermap.org/data/2.5/weather?q=" + city + "&appid=b6907d289e10d714a6e88b30761fae22"
r = requests.get(url=urlx)
output = r.json()

print("Raw JSON \n")
print(output)
print("\n")

citylongitude = output['coord']['lon']
citylatitude = output['coord']['lat']
print("Longitude: " + str(citylongitude) + " , " + "Latitude: " + str(citylatitude))

內容解密:

  1. 傳送GET請求:使用requests.get向指定的API URL傳送GET請求。
  2. 解析JSON回應:將API回應解析為JSON格式。
  3. 提取有用資訊:從JSON回應中提取城市的經度和緯度。

使用正規表示式(regex)

正規表示式是一種強大的工具,用於從文字中提取特定模式的資料。以下是一個使用Python中的regex提取月份、年份和時間的範例:

import re

sample = "From Jan 2018 till Nov 2018 I was learning python daily at 10:00 PM"
print(re.split('\W+', sample))

regex = re.compile('(?P<month>\w{3})\s+(?P<year>[0-9]{4})')
for m in regex.finditer(sample):
    value = m.groupdict()
    print("Month: " + value['month'] + " , " + "Year: " + value['year'])

regex = re.compile('\d+:\d+\s[AP]M')
m = re.findall(regex, sample)
print(m)

內容解密:

  1. 分割字串:使用\W+將輸入字串分割成單詞。
  2. 提取月份和年份:使用regex模式提取三個字母的月份和四位數的年份。
  3. 提取時間:使用regex模式提取時間(hh:mm AM/PM)。

處理檔案

在網路自動化中,經常需要讀寫檔案以儲存或檢索資料。以下是一個簡單的範例,示範如何根據使用者輸入儲存記錄到CSV檔案:

getinput = input("Do you want to store a new record (Y/N) ")
getinput = getinput.strip().lower()

if "y" in getinput:
    readvaluename = input("Enter the Name: ")
    readvalueage = input("Enter the Age: ")
    readvaluelocation = input("Current location: ")
    tmpvariable = readvaluename + "," + readvalueage + "," + readvaluelocation + "\n"
    fopen = open("myrecord.csv", "w")
    fopen.write(tmpvariable)
    fopen.close()

內容解密:

  1. 檢查使用者輸入:詢問使用者是否要儲存新記錄,並將輸入轉換為小寫以便比較。
  2. 讀取記錄資訊:如果使用者同意儲存,則讀取姓名、年齡和目前位置。
  3. 寫入CSV檔案:將記錄資訊格式化為CSV格式,並寫入名為myrecord.csv的檔案中。

這些基礎概念對於網路自動化至關重要,包括安全地處理憑證、與API互動、使用正規表示式處理文字資料以及讀寫檔案。透過掌握這些技能,網路工程師可以更有效地自動化網路任務,提高效率並減少錯誤。

網路自動化的基礎概念:技術決策與工具整合

在網路自動化領域,工程師經常面臨選擇合適的程式語言來完成特定任務的挑戰。以Python和PowerShell為例,這兩種語言各有其優勢和適用場景。

Python 與 PowerShell 的選擇

Python因其跨平台的特性和對多種網路裝置及供應商的支援,成為與基礎設施裝置互動的首選語言。另一方面,PowerShell在Windows平台上具有無可比擬的優勢,能夠實作深度的系統整合和操作。選擇Python還是PowerShell,主要取決於具體的工作環境和需求。

PowerShell 的優勢

  • Windows 整合度高:PowerShell是Windows環境下的強大工具,能夠直接與系統深度整合,執行諸如程式管理等任務。
  • 內建函式庫:PowerShell擁有豐富的內建函式庫,能夠支援多種任務,無需額外匯入第三方函式庫。
  • Microsoft 支援:作為Microsoft官方支援的工具,PowerShell不斷獲得更新和改進。

PowerShell 程式設計例項

API 存取

以下是一個使用PowerShell呼叫天氣API取得特定城市(例如倫敦)的座標的例子:

# 設定城市名稱
$city = "london"
$urlx = "https://samples.openweathermap.org/data/2.5/weather?q=" + $city + "&appid=b6907d289e10d714a6e88b30761fae22"

# 使用 GET 方法呼叫 API
$stuff = Invoke-RestMethod -Uri $urlx -Method Get

# 輸出原始 JSON 資料
$stuff

# 輸出經度和緯度
Write-Host ("Longitude: " + $stuff.coord.lon + " , " + "Latitude: " + $stuff.coord.lat)

輸出結果如下:

coord : @{lon=-0.13; lat=51.51}
weather : {@{id=300; main=Drizzle; description=light intensity drizzle; icon=09d}}
base : stations
main : @{temp=280.32; pressure=1012; humidity=81; temp_min=279.15; temp_max=281.15}
visibility : 10000
wind : @{speed=4.1; deg=80}
clouds : @{all=90}
dt : 1485789600
sys : @{type=1; id=5091; message=0.0103; country=GB; sunrise=1485762037; sunset=1485794875}
id : 2643743
name : London
cod : 200
Longitude: -0.13 , Latitude: 51.51

與本地機器互動

PowerShell能夠輕鬆地與本地Windows機器互動,例如列出特定的系統程式:

Get-Process `
| Where-Object {$_.Company -like '*Microsoft*'} `
| Where-Object {($_.ProcessName -like '*System*') -or ($_.ProcessName -like '*powershell*')} `
| Format-Table ProcessName, Company -auto

輸出結果如下:

ProcessName Company
---
-
---
---
- 
---
-
---
powershell Microsoft Corporation
powershell_ise Microsoft Corporation
SystemSettings Microsoft Corporation
SystemSettingsBroker Microsoft Corporation

程式碼版本控制與 Git

在網路自動化專案中,程式碼的管理和分享至關重要。Git作為一個版本控制系統,能夠幫助團隊成員協作開發、跟蹤變更並儲存程式碼。

建立 GitHub 帳戶和初始化 Git

  1. 建立 GitHub 倉函式庫:存取 GitHub,建立一個新的倉函式庫,例如命名為 mytest
  2. 安裝 Git 使用者端:從 Git 官網 下載並安裝適合您作業系統的 Git 使用者端。
  3. 克隆倉函式庫到本地:使用命令列工具執行 git clone https://github.com/yourusername/mytest.git 將倉函式庫克隆到本地。

內容解密:

  • 步驟解析:上述步驟展示瞭如何建立一個GitHub倉函式庫並將其克隆到本地。首先,需要在GitHub上建立一個新的倉函式庫;接著,下載並安裝Git使用者端;最後,透過命令列工具將遠端倉函式庫克隆到本地機器上。
  • 技術原理:Git是一種分散式版本控制系統,能夠記錄每次變更並允許多個開發者協作。GitHub則提供了一個根據Web的Git儲存函式庫託管服務,方便團隊成員分享和管理程式碼。

網路自動化基本概念 Chapter 1

Git 環境設定與程式碼提交

在進行網路自動化之前,我們需要了解如何使用 Git 來管理我們的程式碼。首先,我們需要在本地電腦上初始化 Git 環境。

初始化 Git 環境

  1. 開啟命令提示字元或終端機,並導航到您的工作目錄。
  2. 輸入 git init 以初始化 Git 環境。
C:\test\mytest>git init

驗證 Git 狀態

使用 git status 命令來驗證目前的 Git 狀態。

C:\test\mytest>git status
On branch master
No commits yet
Untracked files:
(use "git add <file>..." to include in what will be committed)
git
nothing added to commit but untracked files present (use "git add" to track)

程式碼提交

現在,我們將提交一個簡單的 Python 指令碼到 Git。

  1. 首先,確認需要提交的檔案存在於目前的目錄中。
Directory of C:\test\mytest
12-Nov-18 03:16 PM <DIR> .
12-Nov-18 03:16 PM <DIR> ..
12-Nov-18 03:12 PM 0 git
12-Nov-18 03:16 PM 34 myfirstcodecheckin.py
2 File(s) 34 bytes
2 Dir(s) 345,064,542,208 bytes free
  1. 使用 git add 命令將檔案新增到 Git 索引中。
C:\test\mytest>git add myfirstcodecheckin.py
C:\test\mytest>git status
On branch master
No commits yet
Changes to be committed:
(use "git rm --cached <file>..." to unstage)
new file: myfirstcodecheckin.py
Untracked files:
(use "git add <file>..." to include in what will be committed)
git
  1. 使用 git commit 命令提交變更。
C:\test\mytest>git commit -m "this is a test checkin"
[master (root-commit) abe263d] this is a test checkin
Committer: Abhishek Ratan <[email protected]>
1 file changed, 1 insertion(+)
create mode 100644 myfirstcodecheckin.py
  1. 最後,使用 git push 命令將變更推播到遠端儲存函式庫。
C:\test\mytest>git push
Counting objects: 3, done.
Writing objects: 100% (3/3), 273 bytes | 273.00 KiB/s, done.
Total 3 (delta 0), reused 0 (delta 0)
remote:
remote: Create a pull request for 'master' on GitHub by visiting:
remote: https://github.com/pnaedition2/mytest/pull/new/master
remote:
To https://github.com/pnaedition2/mytest.git
* [new branch] master -> master

#### 內容解密:

此段落展示瞭如何使用 Git 管理程式碼,包括初始化 Git 環境、驗證 Git 狀態、提交程式碼以及將變更推播到遠端儲存函式庫。其中,git init 用於初始化 Git 環境,git status 用於檢視目前的 Git 狀態,git add 用於將檔案新增到 Git 索引中,git commit 用於提交變更,而 git push 則用於將變更推播到遠端儲存函式庫。

使用案例

第一種使用案例

假設有一家旅行社有三位客戶。我們的任務是根據預先定義的偏好,為任意兩位客戶建議特定城市的旅遊套餐。此外,還需要提供未來五天的天氣預報。為了提升使用者經驗,我們還會詢問客戶一個問題,以確定他們的入住時間和交通方式。

以下是程式碼範例:

import getpass
import base64
import requests
from collections import Counter
import re

# 請求使用者輸入使用者名稱和密碼
uname = input("Enter your username :")
p = getpass.getpass(prompt="Enter your password: ")

# 組合憑證並加密
creds = uname + "*.*" + p

# 已註冊客戶的加密憑證字典
customers = {
    "customer1": b'Y3VzdG9tZXIxKi4qcGFzc3dvcmQx',
    "customer2": b'Y3VzdG9tZXIyKi4qcGFzc3dvcmQy',
    "customer3": b'Y3VzdG9tZXIzKi4qcGFzc3dvcmQz'
}

### 解密給定的憑證
def decryptcredential(pwd):
    rvalue = base64.b64decode(pwd)
    rvalue = rvalue.decode()
    return rvalue

### 加密給定的憑證
def encryptcredential(pwd):
    rvalue = base64.b64encode(pwd.encode())
    return rvalue

# 驗證客戶是否合法的旗標
flag = True

### 已驗證客戶的處理程式
def validatedcustomer(customer):
    print("Hello " + customer)
    inputcity = input("Which city do you want to travel (ex London/Paris/Chicago): ")
    inputaddinfo = input("Any specific checkin time [AM/PM] and preferred mode of travel [car/bus]: ")
    
    #### 從額外資訊中提取正規表示式值
    regex = re.compile('\d+:\d+\s[AP]M')
    time = re.findall(regex, inputaddinfo)
    if "car" in inputaddinfo:
        transport = "car"
    else:
        if "bus" in inputaddinfo:
            transport = "bus"
    
    ### 根據額外資訊建立句子
    print("\n\nYou have selected to checkin at " + time[0] + ", and your preferred transport will be " + transport + " .")
    getcityinfo = validatecity(inputcity)
    
    ### 將字典按照天氣型別從高到低排序
    sorted_d = [(k, getcityinfo[k]) for k in sorted(getcityinfo, key=getcityinfo.get, reverse=True)]
    
    ### 迭代天氣資料以建立句子
    sentence = "Weather prediction for next 5 days is (chance of) "
    for item in sorted_d:
        sentence = sentence + " " + item[0] + ": " + str(item[1]) + "%,"
    print(sentence)

### 驗證城市未來五天的平均天氣
def validatecity(inputcity):
    # 建立空列表和字典來儲存天氣資料
    weathers = []
    weatherpercentage = {}
    
    # 去除輸入城市名稱中的額外空格
    inputcity = inputcity.strip()
    
    # 組合 API 請求 URL
    urlx = "https://samples.openweathermap.org/data/2.5/forecast?q=" + inputcity + "&appid=b6907d289e10d714a6e88b30761fae22"
    
    # 傳送 GET 請求到 URL
    r = requests.get(url=urlx)

#### 內容解密:

此段落展示了一個旅行社根據客戶偏好提供旅遊套餐建議和天氣預報的案例。程式碼中使用了 input()getpass() 函式來取得使用者輸入,使用者名稱和密碼被組合並加密。程式碼還定義了兩個函式:decryptcredential() 用於解密憑證,encryptcredential() 用於加密憑證。此外,程式碼還定義了兩個主要函式:validatedcustomer() 用於處理已驗證客戶的請求,validatecity() 用於驗證城市的天氣預報。這些函式使用了 requests 函式庫來傳送 API 請求以取得天氣資料。