Python Capture reply from powershell

2020-05-09 17:01发布

The code below works when typed manually however when I run the program.py nothing prints. My ultimate goal is to retrieve this data from user pc to create an easy way to recreate shortcuts.... My users somehow lose them lol

import smtplib, os, subprocess, sys
from string import ascii_uppercase
from cStringIO import StringIO

data = os.popen(r"dir %userprofile%\desktop\*.lnk* /s/b").read()
file = open("testitem.txt", "w")
file.write(data)
file.close()


my_data = dict(zip(ascii_uppercase,open("testitem.txt")))


old_stdout = sys.stdout
sys.stdout = mystdout = StringIO()

for key, value in my_data.iteritems():
    subprocess.Popen([r"powershell.exe", "$sh = New-Object -COM WScript.Shell" + "\n" +     "$sh.CreateShortcut(\"%s\").TargetPath" % my_data[key].replace("\n", "")], stdout=subprocess.PIPE).communicate()[0]


sys.stdout = old_stdout

shared = mystdout.getvalue()
print shared

1条回答
放荡不羁爱自由
2楼-- · 2020-05-09 17:27

try removing this sys.stdout = old_stdout line and add stdout=sys.stdout to your main process line for ex like .Popen(***,stdout=sys.stdout)

查看更多
登录 后发表回答