saswati das saswati das - 1 month ago 12
Git Question

execute git command in a remote machine using paramiko

I have written a code to execute git command in a remote server but i never executed


Step 1: Login to remote server

Step 2: change dir to git repository

Step 3: execute git clean -fdx command


Below is the sample code

try:
ssh = paramiko.SSHClient()
sssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(dummyipaddress, username="john", password="philips")
except (paramiko.BadHostKeyException, paramiko.AuthenticationException,paramiko.SSHException) as e:
print str(e)
sys.exit(-1)
try:
channel = ssh.get_transport().open_session()
channel.send("cd /path to git dir"+ '\n')
time.sleep(5)
print channel.recv(1024)
channel.send("git clean -fdx"+'\n')
print chan.recv(1024)
except paramiko.SSHException as e:
print str(e)
sys.exit(-1)


But the issue is that i can able to change to git repository but not able to execute git command

Answer

You need to start a shell before sending shell commands:

channel = ssh.get_transport().open_session()
channel.get_pty()         # get a PTY
channel.invoke_shell()    # start the shell before sending commands
channel.send("cd /path to git dir"+ '\n')
time.sleep(5)
print channel.recv(1024)
channel.send("git clean -fdx"+'\n')
print chan.recv(1024)