Save variable from my PC to .txt file on Remote Windows Server using Python + WMI

Question:

I have a Python script on my PC with the variable x. I would like to write x‘s value to a .txt file on Remote Windows Server 2019.

I launched this Python code on my PC:

import wmi

x = 28
c = wmi.WMI(ip, user=username, password=password)
process_id, return_value = c.Win32_Process.Create(CommandLine=f"cmd.exe /c set x={x} & echo %x% > c:/1.txt")

Connection works fine but I expected that the file c:/1.txt on the remote server would contain the value of the variable x, i.e. the number 28, but the .txt file "c:/1.txt" on the Remote Windows Server contains %x%

Asked By: jobberman

||

Answers:

Because you’re using an f-string, its probably better to forgo the shell variable and format x into the echo command directly:

import wmi

x = 28
c = wmi.WMI(ip, user=username, password=password)
process_id, return_value = c.Win32_Process.Create(CommandLine=f"echo {x} > c:/1.txt")
Answered By: Michael M.
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.