如何在powershell和python脚本中保护API身份验证详细信息

2024-10-06 10:07:09 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我使用Powershell和Python作为脚本的一部分来访问和使用api。在

但问题是我必须输入用户和pass等,并将其留在脚本中。目前我所做的唯一一件事就是在脚本中输入凭证的base128编码,并在后面加上一行解码。在

我不想不得不在一个对话框中输入我的密码,因为这意味着许多API的快速自动化。脚本+资源是可移植的,这意味着我把它们带到其他多台计算机上,然后按原样运行。在

如何使其更符合我的要求? 有没有类似lastpass类型的程序/API,我可以用它检索适当的凭证,甚至可能从网络文件夹/数据库中?在

任何帮助都会很好。在

谢谢


Tags: 用户脚本api密码编码pass资源解码
1条回答
网友
1楼 · 发布于 2024-10-06 10:07:09

To store and retrieve encrypted credentials easily, use PowerShell's built-in XML serialization (Clixml):

$credential = Get-Credential

$credential | Export-CliXml -Path 'C:\My\Path\cred.xml'

To re-import:

$credential = Import-CliXml -Path 'C:\My\Path\cred.xml'

The important thing to remember is that by default this uses the Windows data protection API, and the key used to encrypt the password is specific to both the user and the machine that the code is running under.

As a result, the encrypted credential cannot be imported by a different user nor the same user on a different computer.

By encrypting several versions of the same credential with different running users and on different computers, you can have the same secret available to multiple users.

By putting the user and computer name in the file name, you can store all of the encrypted secrets in a way that allows for the same code to use them without hard coding anything:

Encrypter

# run as each user, and on each computer

$credential = Get-Credential

$credential | Export-CliXml -Path "C:\My\Secrets\myCred_${env:USERNAME}_${env:COMPUTERNAME}.xml"

The code that uses the stored credentials:

$credential = Import-CliXml -Path "C:\My\Secrets\myCred_${env:USERNAME}_${env:COMPUTERNAME}.xml"

The correct version of the file for the running user will be loaded automatically (or it will fail because the file doesn't exist).

相关问题 更多 >