简体   繁体   中英

Executing Git server commands through Python shell

I'm trying to write my own shell script in Python for SSH to call to (using the SSH command= parameters in authorized_keys files). Currently I'm simply calling the original SSH command (it is set as an environment variable prior to the script being called my SSH). However, I always end up with a git error regarding the repository hanging up unexpectedly.

My Python code is literally:

#!/usr/bin/python
import os
import subprocess

if os.environ('SSH_ORIGINAL_COMMAND') is not None:
    subprocess.Popen(os.environ('SSH_ORIGINAL_COMMAND'), shell=True)
else:
    print 'who the *heck* do you think you are?'

Please let me know what is preventing the git command from successfully allowing the system to work. For reference, the command that is being called on the server when a client calls git push is git-receive-pack /path/to/repo.git .

Regarding the Python code shown above, I have tried using shell=True and shell=False (correctly passing the command as a list when False ) and neither work correctly.

Thank you!

Found the solution!

You'll need to call the communicate() method of the subprocess object created by Popen call.

proc = subprocess.Popen(args, shell=False)
proc.communicate()

I'm not entirely sure why, however I think it has to do with the communicate() method allowing data to also be given via stdin . I thought the process would automatically accept input since I didn't override the input stream at all anywhere, but perhaps a manual call to communicate is needed to kick things off...hopefully someone can weigh in here!

You also can't stdout=subprocess.PIPE as it will cause the command to hang. Again, not sure if this is because of how git works or something to do about the whole process. Hopefully this at least helps someone in the future!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM