【问题标题】:How to connect to an SMB share and write to a file in Powershell without mounting?如何在不挂载的情况下连接到 SMB 共享并写入 Powershell 中的文件?
【发布时间】:2021-02-18 06:49:41
【问题描述】:

我浏览了文档here。奇怪的是,我找不到任何提及如何使用 PowerShell 简单地连接到(not mount)SMB 共享的内容。我在 Python 中寻找相当于 this 的东西:

with smbclient.open_file(args.share, username=args.smbuser, password=args.smbpass, mode='w', encoding='utf-8-sig', newline='') as file:
  file.write("stuff")

【问题讨论】:

  • 这能回答你的问题吗? "net use" in PowerShell without specifying drive
  • @marsze 我不这么认为?文档非常稀缺-也许如果我在写出文件的示例中看到它?我认为这可能是答案的一部分,因为New-SmbMapping 是我排队的那个,但目前尚不清楚如何使用它从脚本中写入文件。

标签: powershell smb cifs


【解决方案1】:

您可以使用 Windows 的 net 实用程序

net use \\server /user:domain\username password

或使用SmbShare 模块中的 PowerShell cmdlet New-SmbMapping

New-SmbMapping -RemotePath '\\server' -Username "domain\username" -Password "password"

之后,您可以简单地使用 UNC 路径写入文件,例如 Out-File

"Your output" | Out-File "\\server\path\myfile.txt"

【讨论】:

  • 我看到 New-SmbMapping 返回一个 MSFT_SmbMapping 对象,但我不清楚如何写入文件。 MS 只记录了两种方法——创建和删除,它们似乎都与写出对象无关。 docs.microsoft.com/en-us/previous-versions/windows/desktop/smb/…。抱歉,我在标题中没有写入文件位 - 我只是在 Python 示例中拥有它。我已经编辑了标题以澄清。那些在我身上 - 我很感激帮助。
  • 通过它的 unc 路径写入它
  • @GrantCurell 您始终可以使用 UNC 路径 (\\server\...) 写入/读取文件。 net useNew-SmbMapping 在您必须首先进行身份验证时才需要。
  • @GrantCurell Powershell 有一个非常广泛的help system。例如,你可以写Get-Help New-SmbMapping -Full
  • @GrantCurell Windows 和 IO API 处理这个问题。有几个选项可以定义是否应缓存凭据,或者映射是否应在注销后保留。正如我所说,如果不需要身份验证,则所有 unc 路径都可以在没有任何映射的情况下工作。
猜你喜欢
  • 2021-03-25
  • 1970-01-01
  • 1970-01-01
  • 2021-05-24
  • 2015-03-15
  • 2019-02-18
  • 2018-07-26
  • 2023-03-08
  • 2015-02-20
相关资源
最近更新 更多