When i run below code i see the process terminates even before completion.
I validated command by running it manually command just works file.
cmssso-util produces output which are about 1200 lines.Can this be a buffer issue.
I validated script by assigning 'ls -ltr' to variable command works fine.
Referred Documentation from below link:
https://pexpect.readthedocs.io/en/stable/_modules/pexpect/run.html
I tried prefixing command by 'bash -c' which did not fix this issue.
I tried to find out how pexpect determines to terminate a process , still could not get any clear documentation.
Please help me.
import pexpect
command = "cmsso-util domain-repoint -m execute --src-emb-admin " + 'sourceVcAdmin' + " --replication-partner-fqdn " + 'destVc' + " --replication-partner-admin " + 'destVcAdmin' + " --dest-domain-name " + 'destDomain'
print("Running command : " + command)
(command_output, exitstatus) = pexpect.run(command ,withexitstatus=1, events={'Enter Source embedded vCenter Server Admin Password :' : '\r\n','Enter Replication partner Platform Services Controller Admin Password :' : '\r\n','All Repoint configuration settings are correct; proceed?(.*)' : 'Y\r\n'})
print("----Command output------------")
print(command_output)
print("-----------------------------")
assert exitstatus is 0 , "Execution Failed"
print("Successfully Completed Embedded Cross Domain Re-pointing ")
I could resolve this issue by using the following code:
import pexpect
try :
command = "cmsso-util domain-repoint -m execute --src-emb-admin " + 'sourceVcAdmin' + " --replication-partner-fqdn " + 'destVc' + " --replication-partner-admin " + 'destVcAdmin' + " --dest-domain-name " + 'destDomain'
print("Running command : " + command)
child = pexpect.spawn(command, timeout=3000,maxread=12000)
child.expect (['Enter Source embedded vCenter Server Admin Password :'],timeout=40000)
child.sendline(<password>)
child.expect (['Enter Replication partner Platform Services Controller Admin Password :'],timeout=40000)
child.sendline(<password>)
child.expect (['All Repoint configuration settings are correct; proceed?(.*)'],timeout=40000)
child.sendline('Y')
child.expect(pexpect.EOF)
print(child.before)
assert(child.status == 0 , "Operation Failed!", "Successfully Completed Embedded Cross Domain Re-pointing")
except:
print("Exception was thrown")
print("debug information:")
print(str(child))
child.close()
exit(1)
This is done by increasing default child = pexpect.spawn(command, timeout=600,maxread=8000)value and maxread parameters
Related
I'm making a script that runs a command line and then shows the output in flask webpage.
The problem I'm facing is that the output is malformed, it looks like this.
img
here's my what I have wrote so far:
import subprocess as sp
#app.route('/harvester/scan',methods=['GET','POST'])
def harv():
domain=request.values.get('domain')
outputt=sp.getoutput("theharvester" + " " + "-d" + " " + domain + " " + "-l 10 -b all" )
return outputt
Function subprocess.getoutput is a legacy one. Try using subprocess.run instead.
Here is the example:
import subprocess
command = 'printf "1\n2"'
out = subprocess.run(command, capture_output=True).stdout.decode()
I'm trying to automate the git push processes using python.
I've succeeded automating all except entering the username and password after the git push command.
This is my code so far:
import subprocess
import sys
add: str = sys.argv[1]
commit: str = sys.argv[2]
branch: str = sys.argv[3]
def run_command(command: str):
print(command)
process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
print(str(process.args))
if command.startswith("git push"):
output, error = process.communicate()
else:
output, error = process.communicate()
try:
output = bytes(output).decode()
error = bytes(error).decode()
if not output:
print("output: " + output)
print("error: " + error)
except TypeError:
print()
def main():
global add
global commit
global branch
if add == "" or add == " ":
add = "."
if branch == "":
branch = "master"
print("add: '" + add + "' commit: '" + commit + "' branch: '" + branch + "'")
command = "git add " + add
run_command(command)
commit = commit.replace(" ", "''")
command = 'git commit -m "' + commit + '"'
run_command(command)
command = "git push origin " + branch
run_command(command)
if __name__ == '__main__':
main()
Is there any way to send the information to the command?
If possible, use a credential helper in order to cache that information (credentials associated to a remote URL).
Check the gitcredential section and "Git Tools - Credential Storage".
git config --global credential.helper
That way, you won't have to enter that information at all.
This is how I solved it:
# make sure to cd into the git repo foler
import subprocess
import sys
import os
msg = input('Type the commit message (+ ENTER):')
repo_directory = os.getcwd()
subprocess.run(["git", "add", "."], cwd=repo_directory)
# commit file
subprocess.run(["git", "commit", "-m", msg], cwd=repo_directory)
# push
subprocess.run(["git", "push"], cwd=repo_directory)
I've successfully mounted the drive using fixed //IP/Folder /Mount/Point while providing interchangable username and password as the NAS has permissions set up which are unique to each user.
My First and Working Attempt:
subprocess.check_call("sudo mount -t cifs -o username="+txtUsername.get()+",password="txtPassword.get()+" //IP/Folder /Mount/Point", shell=true)
However after wanting to create a more felxible program i wanted to be able to change the IP and Folder as well as the Mount Point through a config menu.
However when I try to build the command and use it with shell=true it doesn't work and returns a "non zero exit status 1" as a response from the try/except.The structure of the command returned is no different from my working attempt, however the way which i insert it is through variables.
try
password = txtPassword.get()
username = txtUsername.get()
localpath = mountPath
serverAddress = ' //'+serverIP + serverPath +' '+localpath
command = serverAddress
print(command)
subprocess.check_output('sudo mount -t cifs -o username='+username+',password='+password+str(command), shell=True)
#If try fails, caputure error type and store in variable
except subprocess.CalledProcessError as e:
print ("error Message:"+str(e))
**** UPDATE ****
I've done as request in turning the command into an argument after doing some research however the result is no different and still returns a "non zero exit status 1"
command = "sudo mount -t cifs -o username="+username+" password="+password + " " + serverAddress+ " " + localpath
print(command)
subprocess.check_output(command.split(), shell=False)
I have written basic port scanner for target ip and when I run it through kali vm it says sh: 1: nmap-F192.168.234.135: not found. but when I run nmap -F 192.168.234.135 ... its perfectly working. Can anyone point out the reason behind it. thanks
import os
def get_nmap(options,ip):
command = "nmap" + options + "" + ip
process = os.popen(command)
result = str(process.read())
return result
print(get_nmap('-F','192.168.234.135'))
Better, using the subprocess module:
def get_nmap(options, ip) :
return subprocess.check_output(["nmap", options, ip])
#end get_nmap
You need to add spaces in the command string. Change it to
command = "nmap " + options + " " + ip
I have been working on a project that takes a MySQL dump and restores a database with the information that a user provides. I keep getting a file can not be found error then my custom error for debugging stating that. OS command has failed.
try:
username = self.username.get()
password = self.password.get()
database = self.database.get()
file = self.filename
print str(username)
print str(file)
test = os.system("mysql -u" + username + " -p" + password + " " + database + " <" + file)
if (test != 0):
print "OS COMMAND FAILED"
else:
print "pass"
print test
except:
print "fail"
print "Unexpected error:", sys.exc_info()[0]
raise
I will also continue to do research just in case I find the solution. I have been looking at the os.system command but the problem goes away if I specify the file name right in the command instead of retrieving it from a variable.
All the variables are pulled from entry boxes. There is no way for a user to type the file name incorectly as the program populates the filename based on a openfiledialog box and does not allow for the user to edit that box.
Error text:
C:/Documents and Settings/XPMUser/Desktop/src/database.sql
root
The system cannot find the file specified.
OS COMMAND FAILED
1
If there is a space in the filename, that will cause the kind of problem you describe. The shell will parse the space as being a delimiter. You may want to do something like
import pipes
...
database + " < " + pipes.quote(filename)
Better yet, use the subprocess module
test = subprocess.call(['mysql', '-u', username, '-p', password, database],
stdin=open(file))