子进程超过某个时间限制时超时

2024-03-29 00:23:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用python的subprocess模块在我的服务器上运行ssh命令来收集它们的磁盘使用情况。我被卡住的一件事是,如果没有在任何服务器中配置ssh,那么子进程会提示输入密码,这会使整个脚本卡住,然后我不得不自愿终止脚本本身。我只想让它释放所有请求密码提示的服务器(没有配置ssh)并继续处理其余的服务器。在

def MyFunction(server):
   msg=""
   ps = subprocess.Popen("ssh -l mygroup %s 'df -k /some/directory'" % server,stdout=subprocess.PIPE,shell=True)
   out, err = ps.communicate()
   if err != None:
      msg += "\n"+err
   else:
      msg = out
   return msg


server_list= ['server A','server B','server C','server D']
for server in server_list:
    Final_msg+=MyFunction(server)

任何帮助都将不胜感激!:)


Tags: 模块命令服务器脚本密码servermsgout
1条回答
网友
1楼 · 发布于 2024-03-29 00:23:24

如果这只是你想避免的事情ssh向你要任何东西,那么你可以禁止它这样做。在

您可以使用SSH选项

BatchMode

If set to “yes”, passphrase/password querying will be disabled. This option is useful in scripts and other batch jobs where no user is present to supply the password. The argument must be “yes” or “no”. The default is “no”.

所以只需添加-o BatchMode=yes

ps = subprocess.Popen("ssh -o BatchMode=yes -l mygroup %s 'df -k /some/directory'" % server, stdout=subprocess.PIPE, shell=True)

顺便说一句,你为什么需要shell=True在这里?做得更好

^{pr2}$

因为它更干净、更安全、内部更简单。在

相关问题 更多 >