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)
Related
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
I'm trying to run terminal commands from a web python script.
I tried many things but none seens to work... Such as: add 'www-data' to sudoers, use full path to bin, run command with sudo word, use 3 different system calls (os.spawnl and subprocess) and none of that works.
Read only commands like "ps aux" that only output information works, but a simple echo to file don't. It seens like need permitions to do so. What more can i try?
Example from output: Unexpected error: (, CalledProcessError(2, '/bin/echo hello > /var/www/html/cgi-bin/test2.htm'), )
On that example the /var/www/html/cgi-bin/ folder is owned by "www-data", same user as server config.
<!-- language: python -->
#!/usr/bin/python3
# coding=utf-8
import os
import sys
import subprocess
import cgi
import subprocess
SCRIPT_PATH = "/var/www/html/scripts/aqi3.py"
DATA_FILE = "/var/www/html/assets/aqi.json"
KILL_PROCESS = "ps aux | grep " + SCRIPT_PATH + " | grep -v \"grep\" | awk '{print $2}' | xargs kill -9"
START_PROCESS = "/usr/bin/python3 " + SCRIPT_PATH + " start > /dev/null 2>&1 &"
STOP_PROCESS = "/usr/bin/python3 " + SCRIPT_PATH + " stop > /dev/null 2>&1 &"
# Don't edit
def killProcess():
os.spawnl(os.P_NOWAIT, KILL_PROCESS)
try:
os.spawnl(os.P_NOWAIT, "/bin/echo hello > /var/www/html/cgi-bin/test2.htm")
proc = subprocess.Popen(['sudo', 'echo', 'hello > /var/www/html/cgi-bin/test3.htm'])
print(subprocess.check_output("/bin/echo hello > /var/www/html/cgi-bin/test2.htm", shell=True, timeout = 10))
except:
print("Unexpected error:", sys.exc_info())
print(KILL_PROCESS)
def stopSensor():
killProcess()
os.spawnl(os.P_NOWAIT, STOP_PROCESS)
def restartProcess():
killProcess()
print(START_PROCESS)
print(os.spawnl(os.P_NOWAIT, START_PROCESS))
def main():
arguments = cgi.FieldStorage()
for key in arguments.keys():
value = arguments[key].value
if key == 'action':
if value == 'stop':
stopSensor()
print("ok")
return
elif value == 'start' or value == 'restart':
restartProcess()
print("ok")
return
elif value == 'resetdata':
try:
with open(DATA_FILE, 'w') as outfile:
outfile.write('[]')
except:
print("Unexpected error:", sys.exc_info())
print("ok")
return
print("?")
main()
I was able to solve my problem with: http://alexanderhoughton.co.uk/blog/lighttpd-changing-default-user-raspberry-pi/
I've been taking an Ethical Hacking course. Part of the course is creating a Python script that finds the password for a locked zip file, from a password list text file (hope that makes sense!) - basically iterates through a text file trying each password. The script doesn't work, doesn't error out, and the instructor says "well, it works for me" - not useful. Here's the script:
import optparse
import zipfile
from threading import Thread
def extract_zip(zfile, password):
try:
zfile.extractall(pwd=password)
print("[+] Password Found: " + password + '\n')
except:
pass
def main():
parser = optparse.OptionParser("usage %prog "+\
"-f <zipfile> -d <dictionary>")
parser.add_option('-f', dest='zname', type='string',\
help='specify zip file')
parser.add_option('-d', dest='dname', type='string',\
help='specify dictionary file')
(options, arg) = parser.parse_args()
if (options.zname == None) | (options.dname == None):
print(parser.usage)
exit(0)
else:
zname = options.zname
dname = options.dname
zFile = zipfile.ZipFile(zname)
passFile = open(dname)
for line in passFile.readlines():
password = line.strip('\n')
t = Thread(target=extract_zip, args=(zFile, password))
t.start()
if __name__ == '__main__':
main()
The other two files are a text file with a list of passwords, and a password protected zip file where one of the passwords from the text file will unlock it.
Within the course there's a thread mentioning that optparse is depracated, and argparse is its replacement - but even rewriting the script with that doesn't work.
For want of closing out this part of the course I'm looking for help in why this doesn't work.
Thanks in advance for any help on this.
Per my comment above - I added the code below just below the "try" statement:
password = bytes(password.encode('utf-8'))
...then changed
print('[+] Password Found: ' + password + '\n')
to
print("[+] Password Found: " + (password.decode("utf-8")) + '\n')
Now I get the password printed to the console, and the zip file is unzipped. Here's the final, working code.
import optparse
import zipfile
from threading import Thread
def extract_zip(zfile, password):
try:
password = bytes(password.encode('utf-8'))
zfile.extractall(pwd=password)
print("[+] Password Found: " + (password.decode("utf-8")) + '\n')
except:
pass
def main():
parser = optparse.OptionParser("usage %prog " + '-f <zipfile> -d <dictionary>')
parser.add_option('-f', dest='zname', type='string', help='specify zip file')
parser.add_option('-d', dest='dname', type='string', help='specify dictionary file')
(options, args) = parser.parse_args()
if (options.zname is None) | (options.dname is None):
print(parser.usage)
exit(0)
else:
zname = options.zname
dname = options.dname
zFile = zipfile.ZipFile(zname)
passFile = open(dname)
for line in passFile.readlines():
password = line.strip('\n')
t = Thread(target=extract_zip, args=(zFile, password))
t.start()
if __name__ == '__main__':
main()
The way I found this was by changing the 'except' statement to print exceptions to the console:
except Exception as e: print(e)
From there I had a couple of issues to solve, but at least I had errors to work with. Once the password was being successfully logged to the console I change the exeception statement back to "pass" - don't need to see the passwords that failed!
I hope this helps someone else hitting the same issues I had.
I run your code using python3 it excuted without problem i did this long ago
it is a book called violent something
the password.txt should contain this line
victim: HX9LLTdc/jiDE: 503:100:Iama Victim:/home/victim:/bin/sh
root: DFNFxgW7C05fo: 504:100: Markus Hess:/root:/bin/bash
and the command should look like
python stack.py -f evil.zip -d passwords.txt
Has anyone been successful in doing this on windows? I'm trying to command a DSLR camera to take photos with Python over USB on a Windows machine. Or do you have a better solution (I am unable to switch to Linux).
Here's a working solution, using Python 3.5 (installed via Anaconda), BTW.
The parameters for the ISO and shutter are hardwired, but this should get you going if you ever need it.
import sys
import os
import subprocess
import datetime
def func_TakeNikonPicture(input_filename):
camera_command = 'C:\Program Files (x86)\digiCamControl\CameraControlCmd.exe'
camera_command_details = '/filename ./' + input_filename + ' /capture /iso 500 /shutter 1/30 /aperture 1.8'
print('camera details = ',camera_command_details)
full_command=camera_command + ' ' + camera_command_details
p = subprocess.Popen(full_command, stdout=subprocess.PIPE, universal_newlines=True, shell=False)
(output, err) = p.communicate()
#This makes the wait possible
p_status = p.wait(1)
# print(p.stdout.readline())
#This will give you the output of the command being executed
print('Command output: ' + str(output))
print('Command err: ' + str(err))
print('done')
if(len(sys.argv) < 2):
rawimagename = 'test.jpg'
else:
# sys.argv[0] is the program name, sys.argv[1] is the first file, etc.
# need to shift this over
files = sys.argv[1:len(sys.argv)]
# Read the image
rawimagename = files[0]
if(os.path.isfile(rawimagename) is True):
print("File exists...not overwriting.")
sys.exit()
# Store date/time for file uniqueness
current_dt=datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
print("Current date time = " + current_dt)
rawimagename=current_dt + '_' + rawimagename
print('Name of raw image will be: ', rawimagename)
# take picture
func_TakeNikonPicture(rawimagename)
Digicamcontrol have a remote utility which can control the application almost all aspects, the utility can be run in command prompt or execute using subprocess.call in Python
For more info about utility command line arguments check this link http://digicamcontrol.com/doc/userguide/remoteutil
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))