run .exe files in multiple devices with python + psexec - python

I'm trying to build a script in python that runs a powershell command (using subprocess python module) , this powershell command use psexec for run a .exe file on all devices within a .txt file previous generated by python but it is not working
Any help/advice?
import subprocess
import sys
import datetime
import os
dt = datetime.datetime.now()
datetime = dt.strftime("%d-%m-%Y-%H-%M")
#creating new file
output = open('C:\Users\U42857\Desktop\Coding\python\mcafee-veriato\output_automatizacion.txt','wt')
#Writing a computer name within the file created
output.write("u43024")
output.close()
#Reading file path
path = output.name
#Running psexec in each pc with the names within the file previously created
run = subprocess.Popen (["psexec64.exe","#"+path+" -c -f .\Veriato_test_automatizacion.EXE"],stdout=sys.stdout)
run.communicate()
Im getting te psexec syntax output error:
PsExec v2.2 - Execute processes remotely
Copyright (C) 2001-2016 Mark Russinovich
Sysinternals - www.sysinternals.com
PsExec executes a program on a remote system, where remotely executed console
applications execute interactively.
Usage: psexec [\\computer[,computer2[,...] | #file]][-u user [-p psswd][-n s][-r servicename][-h][-l][-s|-e][-x][-i [session]][-c [-f|-v]][-w directory][-d][-<priority>][-a n,n,...] cmd [arguments]
-a Separate processors on which the application can run with
commas where 1 is the lowest numbered CPU. For example,
to run the application on CPU 2 and CPU 4, enter:
"-a 2,4"
-c Copy the specified program to the remote system for
execution. If you omit this option the application
must be in the system path on the remote system.
-d Don't wait for process to terminate (non-interactive).
-e Does not load the specified account's profile.
-f Copy the specified program even if the file already
exists on the remote system.
-i Run the program so that it interacts with the desktop of the
specified session on the remote system. If no session is
specified the process runs in the console session.
-h If the target system is Vista or higher, has the process
run with the account's elevated token, if available.
-l Run process as limited user (strips the Administrators group
and allows only privileges assigned to the Users group).
On Windows Vista the process runs with Low Integrity.
-n Specifies timeout in seconds connecting to remote computers.
-p Specifies optional password for user name. If you omit this
you will be prompted to enter a hidden password.
-r Specifies the name of the remote service to create or interact.
with.
-s Run the remote process in the System account.
-u Specifies optional user name for login to remote
computer.
-v Copy the specified file only if it has a higher version number
or is newer on than the one on the remote system.
-w Set the working directory of the process (relative to
remote computer).
-x Display the UI on the Winlogon secure desktop (local system
only).
-arm Specifies the remote computer is of ARM architecture.
-priority Specifies -low, -belownormal, -abovenormal, -high or
-realtime to run the process at a different priority. Use
-background to run at low memory and I/O priority on Vista.
computer Direct PsExec to run the application on the remote
computer or computers specified. If you omit the computer
name PsExec runs the application on the local system,
and if you specify a wildcard (\\*), PsExec runs the
command on all computers in the current domain.
#file PsExec will execute the command on each of the computers listed
in the file.
cmd Name of application to execute.
arguments Arguments to pass (note that file paths must be
absolute paths on the target system).
-accepteula This flag suppresses the display of the license dialog.
-nobanner Do not display the startup banner and copyright message.
You can enclose applications that have spaces in their name with
quotation marks e.g. psexec \\marklap "c:\long name app.exe".
Input is only passed to the remote system when you press the enter
key, and typing Ctrl-C terminates the remote process.
If you omit a user name the process will run in the context of your
account on the remote system, but will not have access to network
resources (because it is impersonating). Specify a valid user name
in the Domain\User syntax if the remote process requires access
to network resources or to run in a different account. Note that
the password and command is encrypted in transit to the remote system.
Error codes returned by PsExec are specific to the applications you
execute, not PsExec.
Any help, advice about how to achieve that?

Split the string " -c -f .\Veriato_test_automatizacion.EXE" with commas.
["psexec64.exe","#"+path,"-c", "-f",".\Veriato_test_automatizacion.EXE"]

Related

Starting batch file via Paramiko on hpc-system leads to an error message [duplicate]

I am trying to run sesu command in Unix server from Python with the help of Paramiko exec_command. However when I am running this command exec_command('sesu test'), I am getting
sh: sesu: not found
When I am running simple ls command it giving me desired output. Only with sesu command it is not working fine.
This is how my code looks like:
import paramiko
host = host
username = username
password = password
port = port
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port,username,password)
stdin,stdout,stderr=ssh.exec_command('sesu test')
stdin.write('Password')
stdin.flush()
outlines=stdout.readlines()
resp=''.join(outlines)
print(resp)
The SSHClient.exec_command by default does not run shell in "login" mode and does not allocate a pseudo terminal for the session. As a consequence a different set of startup scripts is (might be) sourced, than in your regular interactive SSH session (particularly for non-interactive sessions, .bash_profile is not sourced). And/or different branches in the scripts are taken, based on an absence/presence of TERM environment variable.
Possible solutions (in preference order):
Fix the command not to rely on a specific environment. Use a full path to sesu in the command. E.g.:
/bin/sesu test
If you do not know the full path, on common *nix systems, you can use which sesu command in your interactive SSH session.
Fix your startup scripts to set the PATH the same for both interactive and non-interactive sessions.
Try running the script explicitly via login shell (use --login switch with common *nix shells):
bash --login -c "sesu test"
If the command itself relies on a specific environment setup and you cannot fix the startup scripts, you can change the environment in the command itself. Syntax for that depends on the remote system and/or the shell. In common *nix systems, this works:
PATH="$PATH;/path/to/sesu" && sesu test
Another (not recommended) approach is to force the pseudo terminal allocation for the "exec" channel using the get_pty parameter:
stdin,stdout,stderr = ssh.exec_command('sesu test', get_pty=True)
Using the pseudo terminal to automate a command execution can bring you nasty side effects. See for example Is there a simple way to get rid of junk values that come when you SSH using Python's Paramiko library and fetch output from CLI of a remote machine?
You may have a similar problem with LD_LIBRARY_PATH and locating shared objects.
See also:
Environment variable differences when using Paramiko
Certain Unix commands fail with "... not found", when executed through Java using JSch

ssh running a command gives different results to running it locally

I have a python script that uses Popen to create an appium server for a simulator on a mac
self.appium_process = subprocess.Popen(["/usr/local/bin/appium", "-a", self.ip, "--nodeconfig", self.node_file_path, "--relaxed-security", "-p", str(appium_port), "-dc", default_capabilities], stdout=log_file, stderr=subprocess.STDOUT)
I created a bash shell script that calls the python script. When I run the script from the local box it works and the appium logs show the connection.
I need to run this remote via ssh however. So I use the following to call the script:
ssh 10.18.66.99 automation_fw/config/testscript.sh
This, however, always ends up with the log showing:
env: node: No such file or directory
I checked and the node app has an extra slash before its called:
$ which node
/usr/local/bin//node
$
I tried changing the path on the machine but no change. How can I get this to run from ssh in the same way as it can run locally on that same box
A
When you are running a command vis SSH you are not starting what's called a login shell (more about that here).
From the details you've shared, I would say it's some thing in your environment (running outside a logged-in shell), more specifically a problem with your $PATH variable. You might want to check /etc/environment or similar paths (depending on your Linux flavour) for the wrong value.

Python - Paramiko isn't running a remote script properly

I am trying to run a script over SSH on a remote computer (the script is located on the remote computer). However, when I run Paramiko, all I'm doing is this:
ssh = paramiko.SSHClient()
ssh.connect(-----blacked out-----)
ssh.exec_command("python script.py")
But it's not even executing the command. The script just runs a couple command line commands. The script.py file works just fine if I run it on the remote computer through the remote computer's terminal, but it won't when I try to use ssh to do it like above with paramiko.
You might need to pass the full path to python and/or to the script, sometimes when not executing in terminal/interactive (tty) mode the path is not found as it does not load the profile scripts you would load during an interactive shell.
Without any info I'd guess that it outputs info which you don't read so it blocks and waits until you do... It's like echoing into the pipe when there is nothing on the other side...
I'd recommend looking into http://stackoverflow.com/a/32758464
I had faced a similar problem. In my case, I was executing another process from the ps1 file and the ps1 file was given in the ssh.exec_command() function.
my code flow was
ssh = paramiko.SSHClient()
ssh.connect(Host, Port, Username, Passsword)
ssh.exec_command(run.ps1)
# ----------------------
# As per the Expectation :
# -> run.ps1 will execute on remote
# -> run.ps1 contains "start-process notepad.exe"
# -> So, it should spawn a fresh notepad process
# ----------------------
But, notepad.exe was not started on the remote system
I made the following changes referring to other solutions :
Converted all single file paths to absolute paths.
Added a wait in the run.ps1 file until the child completes its execution
Passed argument in exec_command as "powershell.exe -File Absolute/path/of/file.ps1"
maintained log file into paramiko code as paramiko.util.log_to_file('sssh.log')
This time I was able to see that Notepad.exe was running in the background
I hope it will help with the above question

Remote shutdown not working in Python

I'm trying to write up a small script using Python 2.7.7 that would ping an IP address and determine whether that PC is turned on or off, and change the power state of that system accordingly. I'm relying heavily on the Python modules subprocess and wakeonlan. I am not having any issues pinging or using WOL, but the shutdown functionality is behaving in a very strange way.
Using the command shutdown -s -t 0 /m \\XXX.XXX.X.X from the command prompt works fine, as well as the following from the Python interactive shell in cmd:
import subprocess
ip = 'XXX.XXX.X.X' # use for example
subprocess.call('shutdown -s -t 0 /m \\\\%s' % ip)
But running the same command in from a Python script is returning this error:
XXX.XXX.X.X: The entered computer name is not valid or remote shutdown is not supported on the target computer. Check the name and then try again or contact your system administrator.(53)
Are there any background behaviors that I'm not thinking about? Perhaps something to do with the subprocess module? Thanks in advance!

How do I run a subprocess using local librairies on a remote server using mounted file systems?

I am using a subprocess to run a program on another machine through a mounted network file system.
For my first step in this project I have been using sshfs mount and wget:
sys_process = subprocess.Popen(wget_exec.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
using the command: wget works perfectly
using the command: /mnt/ssh_mount/wget does not execute
System libraries:
my remote system is: Arch Linux which is calling for libpcre.so.1
my local system is: Ubuntu which uses libpcre3 so libpcre.so.1 is missing
I know this because when I call the wget command through the ssh mount (/mnt/ssh_mount/bin/wget) it throws an error. I do not wish to install needed libraries to all systems using this as it defeats the purpose of trying to run something remotely.
For measure checks for permissions have been made
How do I get the command to use the local libraries?
I hope to use nfs as well which would exclude below as solutions:
Python subprocess - run multiple shell commands over SSH
Paramiko
I have tried (with no success)
os.chdir('/mnt/ssh_mount')
Error while loading shared libraries: 'libpcre.so.0: cannot open shared object file: No such file or directory' assumes a stable mount point which would cause changes in 2 places when the environment would change (this seems wrong from a database normalization background, I would assume code/sys admin as well)
You are not actually running the wget command on the remote machine - you are trying to run the remote machine's binary on your local system, and the command is failing due to incompatible library versions. sshfs, nfs, and other types of network mounting protocols simply mount the remote filesystem as an extension of your local one - they don't allow for remote execution. To do that, you'll need to open a remote shell using ssh tunneling and execute the Arch wget command through that.

Categories