使用paramiko在远程机器上执行git命令

时间:2016-10-25 03:39:22

标签: python git ssh paramiko

我编写了一个代码,用于在远程服务器中执行git命令,但我从未执行过

  

步骤1:登录远程服务器
  第2步:将dir更改为git repository
  第3步:执行git clean -fdx命令

以下是示例代码

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)

但问题是我可以更改为git存储库但无法执行git命令

1 个答案:

答案 0 :(得分:0)

您需要在发送shell命令之前启动shell:

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)