I am working on running an executable through python to connect to a cyberarc vault. When i run executable in command line it works, but in python i am not able to get the result.
I have tried both os.system and subprocess but no help.
Please help
import os
import subprocess
prg = "D:\File\CyberArk\ApplicationPasswordSdk\CLIPasswordSDK.exe"
arg = "GetPassword /p AppDescs.AppID=XXXXX-X-1 /p Query=XXXXXXXXXXXXXXXXX;Object=XXXXXXXX-USERID /o Password"
passw = os.system('prg arg') # I have this and as well below with subprocess
passw = subprocess.Popen([r'prg', 'arg'])
print(passw)
In command line below will work -
"D:\File\CyberArk\ApplicationPasswordSdk\CLIPasswordSDK.exe" GetPassword /p AppDescs.AppID=XXXXX-X-1 /p Query=XXXXXXXXXXXXXXXXX;Object=XXXXXXXX-USERID /o Password
It tries to execute prg arg in the CMD, simpy remove the '
passw = os.system(prg + " " + arg)
should work
Related
Need help in calling .bat file via python in windows server.
Currently the .bat file is used to encrypt the password and generate password file .
when the admin run this .bat file, they ll execute below command
runbatch.bat filename
On executing the above it prompt us to enter password
....Enter the password to encrypt
On entering the password it generate the password file in the specified folder.
Now the requirement is to call this .bat file via python.
Reason behind this to create an API and give option to user to generate the password file from their end. When user tries to generate the password file it prompts for password and password file name and passes those parameters to python script which in return calls a .bat file
I am not sure how to echo password input as we do directly in cmd.
Echo password| runbatch.bat filename
In python I have defined .bat location on os.dir and using popen subprocess option to run the.bat` but not sure how to pass password to the command.
import sys
import os
import subprocess
sPassword = $Password
sPasswordFile = $PasswordFile
sInstance = "D:/API/bin" os.chdir(sInstance)
ScriptName = sInstance + "/encryptpassword.bat"
command = '%s "%s"' % (ScriptName, sPasswordFile)
p = subprocess.Popen(command) retcode = p.wait()
Any help will be highly appreciated.
I want to redirect o/p of shell commands to file using variable "path" but it is not working
import os, socket, shutil, subprocess
host = os.popen("hostname -s").read().strip()
path = "/root/" + host
if os.path.exists(path):
print(path, "Already exists")
else:
os.mkdir("Directory", path , "Created")
os.system("uname -a" > path/'uname') # I want to redirect o/p of shell commands to file using varibale "path" but it is not working
os.system("df -hP"> path/'df')
I think the problem is the bare > and / symbols in the os.system command...
Here is a python2.7 example with os.system that does what you want
import os
path="./test_dir"
command_str="uname -a > {}/uname".format(path)
os.system(command_str)
Here's a very minimal example using subprocess.run. Also, search StackOverflow for "python shell redirect", and you'll get this result right away:
Calling an external command in Python
import subprocess
def run(filename, command):
with open(filename, 'wb') as stdout_file:
process = subprocess.run(command, stdout=subprocess.PIPE, shell=True)
stdout_file.write(process.stdout)
return process.returncode
run('test_out.txt', 'ls')
Here is my situation :
We have sqlplus set up in a remote machine and I want to connect to that remote machine and then run sqlplus to execute sql queries. I am trying to write a python script to do that.
Here is my code:
import sys
import getpass
import paramiko
import time
user=raw_input('Enter User Name :')
#host_name=raw_input('Enter Host Name:')
psswd=getpass.getpass()
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('xxx.hostname.xxx',port=22, username=user, password=psswd)
command='export ORACLE_HOME=/opt/app/oracle/product/10.2.0.2/client export LD_LIBRARY_PATH=$ORACLE_HOME/lib \
sudo -S -H /XX/XX/XX/bin/sqlplus'
print 'running remote command'
print(command)
stdin, stdout, stderr=ssh.exec_command(command)
stdin.write(psswd+'\n')
stdin.flush()
for out in stdout.readlines():
print out
ssh.close()
I have two issues here
First is if i pass command like this
'export ORACLE_HOME=/opt/app/oracle/product/10.2.0.2/client export LD_LIBRARY_PATH=$ORACLE_HOME/lib \
sudo -S -H /XX/XX/XX/bin/sqlplus' +' echo $ORACLE_HOME'
I get an empty response even if I have added echo that means that variable is not set correctly.
Secondly, I can't figure out what next to do here. How to provide username/password to sqlplus to allow executing sql queries and then how to supply sql statements.
I had a similar issue as you and eventually wrote a library to do this. Here's a snippet of 'psuedo psuedo code' that should point you in the right direction.
Keep in mind these are methods of a class and you'll need to adapt this pseudo code to your needs. Keep in mind you'll already need a SSHConnection from paramiko here.
def sqlplus_cmd(self, command):
# Create string which exports environmental variables from OracleEnv class ()
if 'CYGWIN' not in <return from 'uname' on the host>:
# If NOT Cygwin, concatenate environmental variable exports
oracle_exports = 'export PATH={0}:$PATH;' \
'export ORACLE_HOME={1};' \
'export ORACLE_SID={2}'.format(<oracle_path>, <oracle_home>, <oracle_sid>)
else:
# If Cygwin, need to source environmental variables for shell session from script
# TODO: May need to get Oracle Home and Path as well for some systems.
self.cmd('echo "export ORACLE_SID={0}" > /tmp/sid'.format(<oracle_sid>))
oracle_exports = 'source /tmp/sid'
# Issue concatinated one line command which exports variables, opens sqlplus, and issues a sqlplus statement
# final_command = oracle_exports + ';' + 'echo "' + command + '" | sqlplus -S / as sysdba'
final_command = '{0};echo "{1}" | sqlplus -S / as sysdba'.format(oracle_exports, command)
stdout, stderr, rc = <paramiko_SSHConnection.exec_command>(final_command)
That should do it. Have fun parsing the output and catching the ORA-xxx and SP2-xxx errors in stdout.
Why don't you split your command into a function, and use subprocess.Popen() to execute it in a subprocess?
from subprocess import *
def run_sql_query(sql_command, connection_string):
session = Popen(['sqlplus', '-S', connection_string], stdin=PIPE, stdout=PIPE, stderr=PIPE)
session.stdin.write(sql_command)
return session.communicate()
Then you can pass your connection string and command as arguments to your function:
con_str = 'xxx.hostname.xxx',port=22, username=user, password=psswd'
cmd = ''export ORACLE_HOME=/opt/app/oracle/product/10.2.0.2/client export LD_LIBRARY_PATH=$ORACLE_HOME/lib sudo -S -H /apollo/env/envImprovement/bin/sqlplus'
print(run_sql_query(con_str, cmd))
Python script is designed to run with elevated credentials, unfortunately
it still prompts me for password
when I enter the correct password it doesn't work
Here is script1, which calls script2 with elevated credentials
import os
import sys, subprocess, socket, string
import wmi, win32api, win32con
import win32com.shell.shell as sh
ASADMIN = '/user:DOMAIN\username'
os.system('"runas /user:DOMAIN\username "D:/Python27/python.exe script2.py sender-ip=10.10.10.10 < password.txt""')
sys.exit(0)
if sys.argv[-1] != ASADMIN:
script = os.path.abspath(sys.argv[0])
params = ''.join([ASADMIN] + ['D:\Python27\python.exe',script] + sys.argv[1:])
sh.ShellExecuteEx(lpVerb='runas',lpFile=sys.executable,lpParameters=params)
sys.exit(0)
Here is script2
import sys, subprocess, socket, string
import wmi, win32api, win32con
for args in [item.strip('sender-ip=') for item in sys.argv[1:]]:
userIP = args
userloggedon = ""
# perform system lookup of IP address
userIP = "\\\\" + userIP
pst = subprocess.Popen(
["D:\pstools\psloggedon.exe", "-l", "-x", userIP],
stdout = subprocess.PIPE,
stderr = subprocess.PIPE
)
out, error = pst.communicate()
userLoggedOn = out.split('\n')[1].strip()
print 'userId={}'.format(userLoggedOn)
f = open('D:\SymantecDLP\Protect\plugins\output.txt', 'w')
f.write('userId={}'.format(userLoggedOn))
output.txt is not created
Any ideas?
EDIT
I also read this thread, How to supply password to runas command when executing it from java
but no matter what I try I keep getting the error
Attempting to start c:\test.bat as user "DOMAIN\username" ...
RUNAS ERROR: Unable to run - c:\test.bat
1326: Logon failure: unknown user name or bad password.
Let's talk about your problems one at the time.
1. It still prompts me for password
In the line
os.system('"runas /user:DOMAIN\username "D:/Python27/python.exe script2.py sender-ip=10.10.10.10 < password.txt""')
you're providing the password to script2. runas command still need a password since is trying to run a program as another user.
2. When I enter the correct password it doesn't work
Well ... The code does'n work that's clear. But, you have to be more specific when asking a question. Right now a look to your code and I can see that you're trying to do ping on a remote machine.
Might the remote machine has a firewall?
Have you tryed doing ping manually?
Edit: The output.txt file is not created, and running the script don't tell you nothing about error writting the file, obviously your code is hitting one of the sys.exit() lines.
You can use PsExec
https://learn.microsoft.com/en-us/sysinternals/downloads/psexec
You can supply a username and password and executing does not need to be elevated to admin:
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][-][-a n,n,...] cmd [arguments]
Use the -e switch to give the same results as Runas /netonly:
-e Does not load the specified account’s profile.
How do I create a user in Linux using Python? I mean, I know about the subprocess module and thought about calling 'adduser' and passing all the parameters at once, but the 'adduser' command asks some questions like password, full name, phone and stuff. How would I answer this questions using subprocess?
I've seen module called pexpect in this question: Can I use Python as a Bash replacement?. Is there any other standard module?
Use useradd, it doesn't ask any questions but accepts many command line options.
On Ubuntu, you could use the python-libuser package
import os
import crypt
password ="p#ssw0rd"
encPass = crypt.crypt(password,"22")
os.system("useradd -p "+encPass+" johnsmith")
You could just use the built-in binaries so just call useradd or something through the subprocess module, However I don't know if there's any other modules that hook into Linux to provide such functionality.
def createUser(name,username,password):
encPass = crypt.crypt(password,"22")
return os.system("useradd -p "+encPass+ " -s "+ "/bin/bash "+ "-d "+ "/home/" + username+ " -m "+ " -c \""+ name+"\" " + username)
This is a solution where shell is false.
#!/bin/env/python
import subprocess
import traceback
import sys
def user_add(username, user_dir=None):
if user_dir:
cmd = ["sudo", "useradd", "-d", user_dir, "-m", username]
else:
cmd = ["sudo", "useradd", username]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = p.communicate()
output = output.strip().decode("utf-8")
error = error.decode("utf-8")
if p.returncode != 0:
print(f"E: {error}")
raise
return output
try:
username = "user"
output = user_add(username)
print(F"Success. {username} is added")
except:
traceback.print_exc()
sys.exit(1)