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.
Related
I have been asked to create a user and password from two files in ubuntu. Below is what i did in python.
import os
with open("users.txt",'r') as file, open("passwords.txt", 'r') as password:
for line in file:
pass
for passw in password:
os.system('useradd ' +line)
os.system('echo +line +passw | chpasswd')
Contents of users.txt
avinash
ananthram
Contents of passwords.txt
lifeisbeautiful
lifeisbeautifulagain
It gives me an error in the last line saying chpasswd: line 1: missing new password. I have tried using os.system("echo +line +passw | chpasswd") but still it gives me the error. Can someone help me through this? Thanks in advance
I am expecting to create users with the password from two files.
You have to loop through the lines in both files simultaneously. Code you provided reads the first line from user file, then loops through all the passwords trying to set those passwords for the first user. By the time you reach read second line in users file you have already reached EOF in password file.
Substitute line and passw in last command with those variables' values.
chpasswd expects user and password delimited by colon, not space
add -n to echo to suppress adding newline character at the end
import os
with open("users.txt",'r') as file, open("passwords.txt", 'r') as password:
for line, passw in zip(file, password):
os.system('useradd ' +line)
os.system(f'echo -n "{line}:{passw}" | chpasswd')
Try this
os.system(f'echo -e "{line}\n{passw}" | chpasswd')
Explanation - The echo command is used to write a string to the standard output, but you are using it to construct the command that you want to pass to chpasswd.
Instead of using echo, you can use the -e option of echo to include a new line in the string being passed to chpasswd.
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
I want to call a .sh file from a python script. This requires sudo permissions and I want to automatically pass the password without getting a prompt. I tried using subprocess.
(VAR1 is variable I want to pass, permissions.sh is the sh file I want to call from python script)
process = subprocess.Popen(['sudo', './permissions.sh', VAR1], stdin = subprocess.PIPE, stdout = subprocess.PIPE)
process.communicate(password)
Then I tried using pexpect
child = pexpect.spawn('sudo ./permissions.sh'+VAR1)
child.sendline(password)
In both cases it still prompts for password on the terminal. I want to pass the password automatically. I do not want to use os modules. How can this be done?
would use pexpect, but you need to tell it what to expect after the sudo as so:
#import the pexpect module
import pexpect
# here you issue the command with "sudo"
child = pexpect.spawn('sudo /usr/sbin/lsof')
# it will prompt something like: "[sudo] password for < generic_user >:"
# you "expect" to receive a string containing keyword "password"
child.expect('password')
# if it's found, send the password
child.sendline('S3crEt.P4Ss')
# read the output
print(child.read())
# the end
# use python3 for pexpect module e.g python3 myscript.py
import pexpect
# command with "sudo"
child = pexpect.spawn('sudo rm -f')
# it will prompt a line like "abhi#192.168.0.61's password:"
# as the word 'password' appears in the line pass it as argument to expect
child.expect('password')
# enter the password
child.sendline('mypassword')
# must be there
child.interact()
# output
print(child.read())
I'm trying to create a powershell script which will enter a password coming from the Credential Manager into the password input of a Python script. In this older post, I found some information on how to start a process with Powershell and then enter some text in the STDIN but for some reason, this method does not work for me. I execute the python script and it just keeps waiting for a password input in the Powershell command line window.
This is the code and it executes the Python script correctly which asks for a password, but nothing happens after that. I can enter the password manually and click enter, but that is not the purpose of course. Then I can just execute the python script by itself.
$executingScriptDirectory = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent
. $executingScriptDirectory\CredMan.ps1
$launcherScript = Join-Path $executingScriptDirectory "launcher.py"
$credTarget = 'some-target-in-credential-manager'
Write-Host "Loading password from Windows credmgr entry '$credTarget' ..."
[object] $cred = Read-Creds $credTarget
if ($cred -eq $null)
{
Write-Host ("No such credential found: {0}" -f $credTarget)
Exit 2
}
# Found the credential; grab the password and boot up the launcher
[string] $password = $cred.CredentialBlob
Write-Host "Launching $launcherScript ..."
Write-Host "Password: '$password'"
$psi = New-Object System.Diagnostics.ProcessStartInfo;
$psi.Arguments = "$launcherScript "
$psi.FileName = "python.exe";
$psi.UseShellExecute = $false; # start the process from its own executable file
$psi.RedirectStandardInput = $true; # enable the process to read from stdin
$p = [System.Diagnostics.Process]::Start($psi);
Start-Sleep -s 2 # wait 2 seconds so that the process can be up and running
$p.StandardInput.WriteLine($password);
$p.WaitForExit()
What could the problem be? The password is requested in the python script with this line and so uses the getpass module.
password = getpass.getpass("Enter your password: ")
Thank you for your help.
If you need any more information, just request it :).
I suppose the Python process does not read the password from the STDIN stream but directly from the terminal the process is attached to. This terminal stream is not subject to any redirects you happen to install before starting the subprocess, so writing to the process's STDIN will not influence this. The fact that you can type your password directly using the keyboard into the Python process and that it accepts it proves me right, I'd say.
In your case you need to tweak the Python process to read the PW from somewhere else, e. g. by passing a special option (totally depending on your Python process of course) or by patching the Python source itself.
Maybe there also are Windows-specific ways to simulate keyboard presses, but that I would call a very ugly a hack and thus cannot recommend.
Alfe, thank you for showing me the right direction to solve this problem.
I've adjusted the python script so that it accepts parameters on the command line and the parameter for the password can be given after the -p option, so like this:
$ script.py -p "password"
To do this from the powershell script, I used this code to first get the credential out of the Windows Credential Manager and give it as a parameter to the python script.
I used an existing script to be able to get the credentials out of the credentials manager, namely the CredMan.ps1 script.
# Get the path of where this script is being invocated to reference to the script files in the same directory as this script.
$executingScriptDirectory = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent
# Include external script to speak with Credential Manager
. $executingScriptDirectory\CredMan.ps1
$launcherScript = Join-Path $executingScriptDirectory "script.py"
$credentialTarget = "name-of-credential-in-manager"
[object] $cred = Read-Creds $credentialTarget
if ($cred -eq $null) {
Write-Host ("No such credential found: {0}" -f $credentialTarget)
Exit 2
}
# Found the credential; Grab the password and execute the script with the password
[string] $password = $cred.CredentialBlob
# Execute python script with password given as parameter
$exe = "python.exe"
&$exe $launcherScript -p $password
Thank you for your help and I hope you understand the given answer.
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.