2015-12-30 105 views
0

我是一个系统管理员,并且一直试图进一步研究编码。我非常喜欢使用python,并且能够做一些很酷的事情。然而,我正在努力的一件事是从本质上调用PowerShell脚本并读取输出(理想情况下不需要将其放到文件中)。与PowerShell的Python交互

这里有两个用例: 1)

elif choice =="2": 
     target = raw_input("Enter your target hostname: ") 
     print "Creating target.ps1 file to establish connection" 
     pstarget = open("pstarget.ps1", "w") 
     pstarget.write("$target = New-Pssession " + target + "\n") 
     pstarget.write("Enter-PSSession $target" + "\n") 
     pstarget.close() 
     print "File created. Initiating Connection to remote host..." 
     os.system("powershell -noexit -ExecutionPolicy Unrestricted secretpath\HealthCheck\pstarget.ps1") 

这降低了我在远程PowerShell会话,我可以做这样的事情让主机,它会输出远程计算机的主机名。

我的主要问题是可以说我能够运行该命令作为我创建的文件的一部分(所以它正在输出响应'get-host')。我怎样才能让它回到python?现在工作的方式是,我被引入到powershell会话中(实际上是嵌套的powershell会话,因为它是在另一台机器上调用shell的powershell会话)。所以,是的,是有可能有这些命令的输出使他们的归途中到Python(也许我想设置响应作为一个变量?)

的第二个问题是这样的:

elif choice == "4": 
      username = raw_input("Unlock AD User (Input username): ") 
      print "Creating target.ps1 file to unlock AD account" 
      psunlock = open("unlocktarget.ps1", "w") 
      psunlock.write("$unlock = Unlock-ADAccount " + username + "\n") 
      psunlock.close() 
      print "File created. Unlocking User Account." 
      os.system("powershell -ExecutionPolicy Unrestricted C:secretpath\Stuff\Code\Python\HealthCheck\unlocktarget.ps1") 
      print "%s's account has been unlocked. Press enter to continue." % username 
      raw_input("Press enter to continue...") 
      os.system("cls") 

在这种情况下,我从来没有明确地在PowerShell会话(从用户/用户界面的角度来看),但可以说有一个错误或从该命令的输出,我想捕获它,有没有可能这样做?

我会很乐意提供任何额外的信息,但我基本上寻找一种方法来最终从Python应用程序运行Exchange管理控制台,这将允许我执行诸如“按(1)列出前25个邮箱按大小“或最终,”按(1)生成完整的环境报告“,该报告运行许多PowerShell命令以获取域/广告/交换信息,以及解析最近的备份文件等以便报告从系统可访问性,延迟,正常运行时间,备份失败,事件日志内容,最近更改以及将所有内容作为一个报告输出。

谢谢!

+0

我只是想知道为什么在地球上,你会想要把额外的努力在一个(IMO)逊色平台调用的PowerShell ?为什么不放弃额外的层并使用纯PowerShell,直接利用.NET的强大功能以及像QAD Exhange工具这样的很棒的cmdlets? –

+1

@AustinFrench所以在python中,我编写了一整套网络工具,可以让我使用nmap进行网络扫描/报告。我还写了几个XML解析器,它们读取我的备份系统日常报告并总结错误。只是到了晚些时候,我才决定将某些系统(比如交换系统)作为基准,并做一些检查,例如“这些服务正在运行吗?告诉我哪些服务不是?”。但是,最大的原因是我对脚本/编程不熟悉。我有一本关于Python的书,并且对它更熟悉。我已经做了一个控制台应用程序,现在,我想扩大,也许PS l8r – Abraxas

回答

3

使用subprocess模块,而不是os.system()(代码here无耻被盗):

from subprocess import Popen, PIPE 

cmd = ['powershell.exe', '-ExecutionPolicy', 'Bypass', '-File', 'C:\\Users\\cobalt\\Documents\\test\\test.ps1'] 

proc = Popen(cmd, stdout=PIPE, stderr=PIPE) 
while True: 
    line = proc.stdout.readline() 
    if line != b'': 
     print(line.strip()) 
    else: 
     break 
+0

谢谢!看了几个选项后,我觉得这是最好的选择。 – Abraxas

1

你应该看织物(http://www.fabfile.org/)。

它意味着正是这些类型的任务。

希望有所帮助。