PowerShell将os.system命令视为字符串,是否可以将其作为命令调用?

问题描述

我正在尝试从Python的os.system()向MS PowerShell发送命令。尽管其他命令可以按预期运行,但ssh命令被视为字符串输入,并且在通过os.system()调用时不起作用。

enter image description here

正常的预期输出是:

enter image description here

有什么办法可以“强制” PowerShell将其视为普通命令?

OpenSSH位于Windows 10的System32目录中,并已适当地添加到系统路径和用户路径。

Python代码(此操作失败)

import os
os.system('powershell ssh-keygen -R 192.168.2.2')

PowerShell命令(有效)

ssh-keygen -R 192.168.2.2

解决方法

回顾一下:问题是您的32位Python进程没有看到64位ssh-keygen实用程序,因为32位进程有一个单独的C:\Windows\System32文件夹。

your own answer的一种更简单且侵入性较小的替代方法是使用Windows目录的虚拟SysNative子文件夹,通过该子文件夹,32位进程可以访问 64位 { {1}}(!)文件夹(32位进程将不同,仅32位二进制文​​件的目录视为System32)。

请注意,这仅对于32位Python版本是必需的。

C:\Windows\System32

如果要通过Windows PowerShell执行此操作:

import os
os.system('%windir%\\SysNative\\OpenSSH\\ssh-keygen -R 192.168.2.2')
,

Python对os模块命令使用32位进程。要在Windows 10中从上面解决问题,请使用以下步骤:

  • 转到System32下的OpenSSH文件夹
  • 复制整个OpenSSH目录
  • 将目录粘贴到SysWOW64(32位进程)中
  • 打开命令提示符,然后重新运行以下代码以确认其有效。
 public IOrderedEnumerable<string> FilteredItems => 
      Items.Where(x => x.ToUpper().Contains(ItemsSearch.ToUpper()))

其他任何ssh命令现在都应该可以通过os模块从python使用。

向@ mklement0致谢,以向我们指出正确的方向。

,

变种1:在命令前使用call operator &

os.system('powershell -NoLogo -NoProfile -NonInteractive -ExecutionPolicy ByPass -command ^& ssh-heygen --% -R 192.168.1.1')

--%停止分析运算符,表示powershell将不会尝试分析其余命令。在您看来,它是没有用的,但是在某些情况下,它是强制性的。

变体2:使用Start-Process

os.system('powershell -NoLogo -NoProfile -NonInteractive -ExecutionPolicy ByPass -command Start-Process -FilePath "ssh-keygen" -ArgumentList @("-R","192.168.1.1")')