【问题标题】:SFTP with Powershell in a batch script在批处理脚本中使用 Powershell 的 SFTP
【发布时间】:2020-02-22 04:07:39
【问题描述】:

我有一个批处理脚本,每晚通过schtasks 在不同的远程 Windows PC(Windows 7 32 位 SP1)上运行。这些 PC 需要通过 FTP 文件与 Linux 服务器之间进行传输。目前使用 FTP,批处理脚本运行良好。

现在 Linux 服务器正在更改为仅使用 SFTP。我想编写一个简短的 PowerShell 脚本,将相同的文件通过 SFTP 传输到服务器/从服务器传输——我已经安装了 Posh-Ssh,以便在这些 Windows 系统(PS 版本 5.1)上的 PowerShell 中使用。

目前执行 FTP 的批处理脚本部分如下所示:

REM make temp file for FTP
echo open pos%STORE%               >  C:\temp\temp.txt
echo username                      >> C:\temp\temp.txt
echo password                      >> C:\temp\temp.txt
echo ascii                         >> C:\temp\temp.txt    
echo cd /path/to/use               >> C:\temp\temp.txt
echo put %USERDOMAIN%.ftp          >> C:\temp\temp.txt
echo put posdaily.txt posdaily.ftp >> C:\temp\temp.txt
echo get prod.txt                  >> C:\temp\temp.txt
echo get posdaily.ftp              >> C:\temp\temp.txt
echo quit                          >> C:\temp\temp.txt

REM **** FTP to put/get files from POS Server ****
echo First Try Connect to POS ....
ftp -iv -s:\temp\temp.txt >> C:\log\Daily.log  2>&1

有没有办法使用相同的temp.txt 来将用户名/密码/put/get 传递给使用 Posh-Ssh 的 PowerShell 脚本?我需要对temp.txt 文件进行哪些更改?

我可以调用一个单独的批处理脚本来运行 PowerShell 脚本——我在以前的批处理脚本中已经这样做了——但我不确定如何编写 PowerShell 脚本——我将在 PowerShell 脚本中使用什么命令/命令使用temp.txt 中的数据?

如果我让它在 PowerShell 中工作,我应该能够在需要执行相同操作的 C# 和 VB 脚本中调用相同的 PowerShell 脚本。

【问题讨论】:

  • 为什么你觉得从 FTP 迁移到 SFTP 意味着你需要从批处理迁移到 PowerShell?
  • @SomethingDark 给我的建议。有没有办法像我在上面使用 FTP 一样在命令行/批处理文件中使用 SFTP?
  • @SomethingDark - 但是如果我让它在 Powershell 中工作,我应该能够在需要做同样事情的 C# 和 VB 脚本中调用同一个 Powershell 脚本。
  • FTP 只是一个可执行文件,因此如果您能找到另一个也可以处理 SFTP 的客户端(如 PuTTY),则可以使用它。对于第二个脚本,您可以轻松地从 C# 或 VBScript 调用批处理脚本。

标签: .net powershell batch-file ftp sftp


【解决方案1】:

有没有办法使用正在创建的同一个 temp.txt 将用户名/密码/put/get 传递给使用 Posh-Ssh 的 Powershell 脚本?

不,你不能。 Posh-Ssh 是一个原生 PowerShell 模块,它不会像 ftp 那样使用脚本。

正如@SomethingDark 已经评论的那样,没有必要为 SFTP 切换到 PowerShell。甚至对于 C#/VB.NET 也不行。 从 C#/VB.NET 调用 PowerShell 脚本和批处理文件有什么区别?

对于批处理文件中的 SFTP,请参阅:
Secure FTP using Windows batch script

我的回答建议使用 (my) WinSCP SFTP client。 WinSCP 实际上可以使用与ftp 类似(但不相同)的脚本。还有一个guide for converting ftp script to WinSCP script


尽管如果您的目标是为 PowerShell/C#/VB.NET 提供相同/相似的代码,您最好使用 SFTP .NET 程序集。见SFTP Libraries for .NET

如果您想要一个原生 .NET 程序集,我会推荐 SSH.NET(尽管它的开发在过去几年中停止了)。 而你实际上是use that already, don't you?

WinSCP 也是has .NET assembly——但它不是一个完全原生的.NET 程序集。另一方面,WinSCP GUI 可以generate a code template for SFTP for all of PowerShell, C#, and VB.NET

虽然您为什么不将您的传输功能实现到自定义程序集中并从所有 PowerShell/C#/VB.NET 中重用它?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-30
    • 2018-04-13
    • 1970-01-01
    • 2015-07-06
    • 2019-08-10
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多