【问题标题】:execute git command in a remote machine using paramiko使用 paramiko 在远程机器上执行 git 命令
【发布时间】:2016-10-25 16:36:05
【问题描述】:

我已经编写了一个代码来在远程服务器上执行 git 命令,但我从未执行过

第 1 步:登录远程服务器
第 2 步:将目录更改为 git 存储库
第三步:执行 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 命令

【问题讨论】:

  • 我在 channel.recv() 中没有得到任何东西

标签: python git ssh paramiko


【解决方案1】:

您需要在发送 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)

【讨论】:

  • 嗨 whjm,如果我想再添加一个 channel.send("git reset --hard") 在 2 个命令后我将如何为我执行此操作 第三个命令未执行
  • channel.send("git reset --hard") -- 你错过了\n
  • 我在第二个命令运行后将 channel.send("git reset --hard"+'\n') 放在 >
  • 不知道您所说的 输出在 > 到底是什么意思。尝试使用pdb 调试它并提供更多信息。如有必要,提出一个新问题,因为在 cmets 中进行长时间的讨论并不容易。
最近更新 更多