Python 使用字符串格式在请求头中发送的JSON负载中隐藏用户名和密码

Python 使用字符串格式在请求头中发送的JSON负载中隐藏用户名和密码,python,json,string,request,formatting,Python,Json,String,Request,Formatting,我有一个带有用户名和密码的参数的函数。我希望使用f字符串或任何类型的字符串格式,这样我就不必在代码中硬编码用户名和密码,而是替换传递给函数的参数,因为它违反了安全要求 除非有另一种可能以JSON发送有效负载,否则有效负载必须采用如下所示的格式。我想这只需要通过JSON发送。如果我试图删除反斜杠,它会在缩进时出错 如何利用字符串格式隐藏用户名和密码,以便在运行时提供这些信息 import requests import sys, pprint, json from getpass import g

我有一个带有用户名和密码的参数的函数。我希望使用f字符串或任何类型的字符串格式,这样我就不必在代码中硬编码用户名和密码,而是替换传递给函数的参数,因为它违反了安全要求

除非有另一种可能以JSON发送有效负载,否则有效负载必须采用如下所示的格式。我想这只需要通过JSON发送。如果我试图删除反斜杠,它会在缩进时出错

如何利用字符串格式隐藏用户名和密码,以便在运行时提供这些信息

import requests
import sys, pprint, json
from getpass import getpass
from multiprocessing import Pool
import yaml
from functools import partial

http_header = {}
url_dict = {}

def getCookie(username, password, ip_addr):

    url = "https://"+ip_addr+"/api/aaaLogin.json"

    # payload = " {\r\n\"aaaUser\":"\
    #           " {\r\n\"attributes\":"\
    #           " {\r\n\"name\": \"admin\",\r\n" \
    #           "  \"pwd\":\"Admin_1234!\"\r\n" \
    #           " }\r\n " \
    #           " }\r\n }\r\n"

    payload = {
        # 'aaaUser':'',
        # 'attributes':'',
        'name': username,
        'pwd': password,
    }
    json_payload = json.dumps(payload)

    headers = {
        'Content-Type': "application/json",
        'Cache-Control': "no-cache",
    }

    try:

        req = requests.request("POST", url=url, data=json_payload, headers=headers, verify=False)
    except:
        print('Failed to obtain auth cookie: %s' % (e))
        sys.exit(1)
    else:
        cookie=req.headers['Set-Cookie']
        # print(cookie)
        return cookie

def genericGetRequest(ip_addr, cookie, apiurl, verb):
    url = 'https://'+ip_addr+apiurl
    http_header["Cookie"]=cookie
    http_header["Host"]=ip_addr
    try:
        req = requests.request(verb, url=url, headers=http_header, verify=False)
    except:
        print("There is a problem with the {} request!".format(verb))
    else:
        return(req)

def getResults(username, password, ip):
    cookie=getCookie(username, password, ip)
    if cookie:
        print("User is logged in. Auth-cookie is  %s\n" % cookie)
        vlan_list = []
        trunk_vlans_dict = {}
        for i in range(1, 49):
            apiurl = f"/api/mo/sys/intf/phys-[eth1/{i}]/.json"
            generic = genericGetRequest(ip, cookie, apiurl, 'GET')
            generic = generic.json()
            imdata = generic['imdata']
            vlan = imdata[0]['l1PhysIf']['attributes']
            trunk_vlans_dict[f"eth1/{i}"] = vlan['trunkVlans']
        vlan_list.append(trunk_vlans_dict)
        print(vlan_list)

if __name__ == '__main__':
    username = input("Enter username: ")
    print("Enter password")
    password = getpass()


    if password:
        deviceListFile = 'nexus_list.yaml'
        with open(deviceListFile) as f:
            deviceList = yaml.load(f)

        num_threads = 5
        print("Retreiving Configuration: ")
        pool = Pool(num_threads)
        partial_getResults = partial(getResults, username, password)
        pool.map(partial_getResults, deviceList)
        pool.close()
        pool.join()
    else:
        print("Passwords do not match. Exiting...")
在使用json转储之后,我得到另一个错误,如下所示。顺便说一句,为了清晰起见,我已经发布了整个代码

ssh://vrxxx@werssefsf:22/sdfsdfsdfsdf/Python_Dev/Test1/pyVENV/bin/python -u /NetworkAutomation/Python_Dev/Test1/nxos_test5.py
Enter username: admin
admin
Enter password
Password: Admin_1234!

/NetworkAutomation/Python_Dev/Test1/nxos_test5.py:82: YAMLLoadWarning: calling yaml.load() without Loader=... is deprecated, as the default Loader is unsafe. Please read https://msg.pyyaml.org/load for full details.
  deviceList = yaml.load(f)
Retreiving Configuration: 
/NetworkAutomation/Python_Dev/Test1/pyVENV/lib/python3.7/site-packages/urllib3/connectionpool.py:847: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  InsecureRequestWarning)
multiprocessing.pool.RemoteTraceback: 
"""
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/multiprocessing/pool.py", line 121, in worker
    result = (True, func(*args, **kwds))
  File "/usr/local/lib/python3.7/multiprocessing/pool.py", line 44, in mapstar
    return list(map(*args))
  File "/NetworkAutomation/Python_Dev/Test1/nxos_test5.py", line 58, in getResults
    cookie=getCookie(username, password, ip)
  File "/NetworkAutomation/Python_Dev/Test1/nxos_test5.py", line 42, in getCookie
    cookie=req.headers['Set-Cookie']
  File "/NetworkAutomation/Python_Dev/Test1/pyVENV/lib/python3.7/site-packages/requests/structures.py", line 52, in __getitem__
    return self._store[key.lower()][1]
KeyError: 'set-cookie'
"""

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/NetworkAutomation/Python_Dev/Test1/nxos_test5.py", line 88, in <module>
    pool.map(partial_getResults, deviceList)
  File "/usr/local/lib/python3.7/multiprocessing/pool.py", line 268, in map
    return self._map_async(func, iterable, mapstar, chunksize).get()
  File "/usr/local/lib/python3.7/multiprocessing/pool.py", line 657, in get
    raise self._value
KeyError: 'set-cookie'

Process finished with exit code 1
ssh://vrxxx@werssefsf:22/sdfsdfsdf/Python_Dev/Test1/pyVENV/bin/Python-u/NetworkAutomation/Python_Dev/Test1/nxos_test5.py
输入用户名:admin
管理
输入密码
密码:Admin_1234!
/NetworkAutomation/Python_Dev/Test1/nxos_test5.py:82:yamloaddwarning:在没有加载程序的情况下调用yaml.load()。。。已弃用,因为默认加载程序不安全。请阅读https://msg.pyyaml.org/load 有关详细信息。
设备列表=yaml.负载(f)
检索配置:
/NetworkAutomation/Python_Dev/Test1/pyVENV/lib/python3.7/site packages/urlib3/connectionpool.py:847:unsecurerequestwarning:正在发出未经验证的HTTPS请求。强烈建议添加证书验证。见:https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-警告
不安全(警告)
multiprocessing.pool.RemoteTraceback:
"""
回溯(最近一次呼叫最后一次):
worker中的文件“/usr/local/lib/python3.7/multiprocessing/pool.py”,第121行
结果=(True,func(*args,**kwds))
mapstar中的文件“/usr/local/lib/python3.7/multiprocessing/pool.py”,第44行
返回列表(映射(*args))
文件“/NetworkAutomation/Python_Dev/Test1/nxos_test5.py”,第58行,在getResults中
cookie=getCookie(用户名、密码、ip)
文件“/NetworkAutomation/Python_Dev/Test1/nxos_test5.py”,第42行,在getCookie中
cookie=req.headers['Set-cookie']
文件“/NetworkAutomation/Python_Dev/Test1/pyVENV/lib/python3.7/site packages/requests/structures.py”,第52行,在__
返回self.\u存储[key.lower()][1]
KeyError:“设置cookie”
"""
上述异常是以下异常的直接原因:
回溯(最近一次呼叫最后一次):
文件“/NetworkAutomation/Python_Dev/Test1/nxos_test5.py”,第88行,在
map(部分获取结果,设备列表)
文件“/usr/local/lib/python3.7/multiprocessing/pool.py”,第268行,在地图中
返回self.\u map\u async(func、iterable、mapstar、chunksize).get()
get中第657行的文件“/usr/local/lib/python3.7/multiprocessing/pool.py”
提升自我价值
KeyError:“设置cookie”
进程已完成,退出代码为1

没有一个简单的例子,很难回答你的问题。还不清楚aaaUser、attributes和ip_addr的用途,但我认为这就是您试图实现的目标:

    import json
    
    def getCookie(username, password, ip_addr):
        payload = {
            'name': username,
            'pwd': password
        }
        return json.dumps(payload)
    
    print(getCookie(username='admin', password='Admin_1234', ip_addr="127.0.0.0"))
    # {"name": "admin", "pwd": "Admin_1234"}

不太可能需要所有新行和字符串格式,您只需要通过dumps方法传递Python字典。

谢谢Johnny。你的建议奏效了。我只需要使用aaaUser和嵌套dict格式的属性,如下所示

payload = {
    'aaaUser': {
    'attributes': {
    'name': username,
    'pwd': password,
}}}
json_payload = json.dumps(payload)

你能展示你想要的结果吗?你的问题不会得到回答,因为你需要创建一个新的问题,因为它与你原来的问题无关。3件事我会改变/尝试,1)学究式的我会改变url=f“https://{ip_addr}/api/aaaLogin.json”,因为它更容易阅读,2)我会测试cookie的值以确保我拥有它,你呢?3) 我会尝试req=requests.request(动词,url=url,headers=http\u header,cookies=cookie,verify=False)并删除http\u header[“cookie”]=cookie。请求为您创建Cookiejar。