Python shell和程序中的不同行为

时间:2021-08-18 17:28:50

I'm using subprocess.Popen to instantiate an ssh-agent, add a key and push a git repository to a remote. To do this I string them together with &&. The code I'm using is

我正在使用subprocess.Popen来实例化一个ssh-agent,添加一个密钥并将一个git存储库推送到一个远程。为此,我将它们与&&串在一起。我正在使用的代码是

subprocess.Popen("eval $(ssh-agent) && ssh-add /root/.ssh/test_rsa && git push target HEAD", shell=True)

When I run this as a .py file I am prompted for the key's password. This seems to work as I get.

当我将其作为.py文件运行时,系统会提示我输入密钥的密码。这看起来像我得到的一样。

Identity added: /root/.ssh/test_rsa (/root/.ssh/test_rsa).

添加了身份:/root/.ssh/test_rsa(/root/.ssh/test_rsa)。

But when it tries to push the repository to the remote, an error occurs.

但是当它试图将存储库推送到远程时,会发生错误。

ssh: connect to host ***.***.***.*** port 22: Connection refused
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

However, if I simply run the same command in the interactive shell, it works. What causes this difference in behaviour, and what can I do to fix this?

但是,如果我只是在交互式shell中运行相同的命令,它就可以工作。导致这种行为差异的原因是什么,我该怎么做才能解决这个问题?

1 个解决方案

#1


1  

The git server was on an aws instance that was being started earlier in the script. There was a check to make sure it was running, but aws seems to report an instance as running once boot has begun. This means that there is a brief time in which the instance is running, but an ssh daemon doesn't exist. Because the script moved very quickly into trying to push, it was falling within this time period and the server was refusing its connection attempt. By the time I would try anything in the interactive shell the instance was running long enough that it was working.

git服务器位于脚本早期启动的aws实例上。有一个检查以确保它正在运行,但是一旦启动开始,aws似乎报告一个实例正在运行。这意味着实例运行的时间很短,但ssh守护程序不存在。因为脚本非常快地移动到尝试推送,所以它在这段时间内落下,并且服务器拒绝其连接尝试。当我在交互式shell中尝试任何东西时,实例运行的时间足够长,以至于它正在工作。

In short, aws says instances are running before the OS has started services.

简而言之,aws表示在OS启动服务之前实例正在运行。

#1


1  

The git server was on an aws instance that was being started earlier in the script. There was a check to make sure it was running, but aws seems to report an instance as running once boot has begun. This means that there is a brief time in which the instance is running, but an ssh daemon doesn't exist. Because the script moved very quickly into trying to push, it was falling within this time period and the server was refusing its connection attempt. By the time I would try anything in the interactive shell the instance was running long enough that it was working.

git服务器位于脚本早期启动的aws实例上。有一个检查以确保它正在运行,但是一旦启动开始,aws似乎报告一个实例正在运行。这意味着实例运行的时间很短,但ssh守护程序不存在。因为脚本非常快地移动到尝试推送,所以它在这段时间内落下,并且服务器拒绝其连接尝试。当我在交互式shell中尝试任何东西时,实例运行的时间足够长,以至于它正在工作。

In short, aws says instances are running before the OS has started services.

简而言之,aws表示在OS启动服务之前实例正在运行。