how to excute powershell script on remote machine using ssh in python - python-3.x

When I ssh to the windows machine it will not be in powershell prompt and I don't know how I'm going to execute the powershell script I have.
I tried the following code without success.
ssh_connect(ip1, " powershell.exe <mtu-read.ps1")
def ssh_connect(address, script):
#key_filename1 = 'id_rsa' #no authentication for now testing
host_user = "Administrator"
try:
process1 = subprocess.Popen("ssh -oStrictHostKeyChecking=no " + host_user + "#" + address + script, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output1 = process1.stdout.readlines()
print(output1)
return output1
except Exception as er2:
print(str(er2) + ' connection issue ')
return "0"
The result I get is that it does not recognize the command in the powershell.

Your syntax is invalid in the powershell call:
powershell.exe -File mtu-read.ps1
Note your working directory or the script file won't be found. I suggest fully-qualifying your script path as a best-practice.
As an aside, I question why you're using python to execute powershell instead of just writing a powershell script and utilizing winrm (native to Windows) instead of ssh.

Related

SSH command varaible not being seen

I am trying to pass a variable using a remote SSH command connection. I want to rename the data file with the station variable. The SSH command is being run on a Windows PC to a Ubuntu PC. When the script is run from Python on the Windows PC it makes the connection but won’t rename the file. Can someone suggest what I am doing wrong?
import paramiko
ssh_client =paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname="192.168.1.xx",username="xx",password="xxxx")
station = "NAA"
stdin,stdout,stderr=ssh_client.exec_command(
"mv /home/pi/vlfrx-tools/data/station.data \
/home/pi/vlfrx-tools/data/$station.dat")
station is variable in Python, not in shell - and you need Python functions, not shell $
string-formatting ("{}".format(station))
cmd = "mv /home/pi/vlfrx-tools/data/station.data \
/home/pi/vlfrx-tools/data/{}.dat".format(station)
print("CMD:", cmd)
stdin, stdout, stderr = ssh_client.exec_command(cmd)
or f-string (f"{station}")
cmd = f"mv /home/pi/vlfrx-tools/data/station.data \
/home/pi/vlfrx-tools/data/{station}.dat"
print("CMD:", cmd)
stdin, stdout, stderr = ssh_client.exec_command(cmd)
or old method with % and %s ("%s" % station)
cmd = "mv /home/pi/vlfrx-tools/data/station.data \
/home/pi/vlfrx-tools/data/%s.dat" % station
print("CMD:", cmd)
stdin, stdout, stderr = ssh_client.exec_command(cmd)
See more on page PyFormat.info
EDIT:
It is not tested but probably you could use $station if you set shell variable using EXPORT - but it still need to use Python to format string.
cmd = "EXPORT station={} ; mv ... .../$station.dat".format(station)
I'm not sure but this shell variable can be temporary and you may n need to set it in every exec_command() which need it.

Executing Commands in multiple devices using Python Code in Putty/Plink

I am trying to execute commands that are in a file and respective host credentials in another file, the target is to pull list of commands from that file and execute the commands in the hosts which are in the Credential file.
The outputs should be routed to another file, I tried to write a code and I was able to achieve on for one device and one command. The output is printing in the screen but with /n for every line not as the desired output.
For now I had placed the command in the same file but my target was to pull the commands in line procedure, Like first line execute the command after that execute the next command.
Please help me in resolving this, I am trying to write it in python.
HOST_CRED.txt:
Hostname <IP> <USERID> <PASSWORD> <command>
import socket
import subprocess
from subprocess import Popen, PIPE, STDOUT
with open("HOST_CRED.txt") as f:
for line in f:
x=line.split()
cmd='plink.exe -ssh '+ x[2] + '#'+ x[1] + ' -pw ' + x[3] + ' ' + x[4]
p=Popen(cmd, stdout=PIPE)
output=p.stdout.read()
print(output)

Shell Command with SoapUI groovy

So I'm trying to run a shell script on an automated SoapUI project which is execute in continuous integration. I need to send a few parameters and an SQL query to the script so I'm trying to execute a command similar to this:
/path/to/file.sh param1 param2 "sql query"
If I log the command and execute it manually it works perfectly but when groovy runs it the "sql query" argument is split into multiple arguments for every space.
I've tried running the command with
String command = "/path/to/file.sh param1 param2 \"sql query\""
def proc = command.execute()
proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(5000)
I'm not getting what I'm doing wrong.
Best regards
In Grooy also arrays (arrays are internal lists) have a execute method. It's usually much safer to execute commands over arrays.
def command = ['/path/to/file.sh', 'param1', 'param2', 'sql query']
def proc = command.execute()
proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(5000)

remote powershell scripts on windows not running through python script in linux

I have a python script written using paramiko and pysphere.this script is in linnux box.i have some powershell scripts on windows machine which i have to run one after the other(after each script ends obviously),but the point here is through my pythonscript it is not running the powershell scripts on windows machine.Kindly help.
PS;i have to run python script fromlinux and powershell scriupts on windows.
Here is a snippet of code for running powershell scripts:
target_vm1 = connect_Esxi_Server(return_list[0])
print "Again connected to vm:" + return_list[0]
target_vm1.login_in_guest(vmUser,vmPass)
list_scripts = target_vm1.list_files(VM_SCRIPT_LOCATION)
for f in list_scripts:
size = f['size']
**if size <> 0:**
paths = f['path']
print paths
#for all_scripts in paths:
*****print "script running is :" , paths*****
path_l = os.path.join(VM_SCRIPT_LOCATION + '\\'+ paths)
*****print path_l*****
run_script =
subprocess.Popen([r'c:\\Windows\\system32\\WindowsPowerShell\\v1.0\\powershell.exe',". path_l"], shell=True)
result = run_script.wait()
print "result is:", result
I doubt whether subprocess will work.
Please note that the bold prints given above are giving the correct script to run.there are many powershell scriptsinside the fo;der,so looping throught it and running each one of them.
Any help would be appreciated,this thing is eating my heads off.....argghhhhhhhh..
Cheers,
NJ
I run powershell commands directly using paramiko:
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('10.10.0.2', username='vipul', password='password')
cmd = "powershell -InputFormat none -OutputFormat text echo Hello"
stdin, stdout, stderr = self.ssh.exec_command(cmd)
print stdout.readlines()
Here 10.10.0.2 is my windows machine. Using cygwin sshd server for ssh.

How to run Azure PowerShell cmd from cloud service

I've developed a web role to manage Azure VM's that is working locally but NOT when it's deployed in a Cloud Service.
I have executed the cmd that is in the web role in PowerShell through an RDP connection to the Cloud Service, so I know PowerShell v3.0 and Azure cmd are working fine.
First steps I had some permissions and certs issues but solved, the problem now is I can't see any error in Event Viewer.
I'm using PowerShell.Create() of System.Automation.dll
string script = "Set-ExecutionPolicy Unrestricted -Force
script = "Import-Module \"D:\\Program Files (x86)\\Microsoft SDKs\\Windows Azure\\PowerShell\\Azure\" 2 >> C:\errorp.out";
script = "Set-AzureSubscription –DefaultSubscription \"Test Environment\"";
script = "Get-AzureVM " + vm
I'm trying to get the error in all the commands with "2 >> C:\errorp.out" (actually is in all commands but didn't copy here) but it creates a blank file.
Am I missing any extra configuration to be able to do that?
The $error variable will have your error history. For example
$error | format-list -property *
Silly mistake: I was creating a new shell for each line of the script
var shell = PowerShell.Create();
So, in the second line, after do "Import-Module Azure", this second shell didn't have access to the Azure commands.
I get this thanks to #Rick for introduce me the $error, however could get working this in C#, what I did instead is:
if (shell.Streams.Error.Count > 0)
{
for (int i = 0; i < shell.Streams.Error.Count; i++)
{
ResultBox.Text += "Error: " + shell.Streams.Error[i] + "\r\n";
}
}

Resources