diff --git a/modules/node/node.module b/modules/node/node.module
index 8f247cd..f1ba73a 100644
--- a/modules/node/node.module
+++ b/modules/node/node.module
@@ -3615,8 +3615,13 @@ function node_access_rebuild($batch_mode = FALSE) {
       batch_set($batch);
     }
     else {
-      // Try to allocate enough time to rebuild node grants
-      drupal_set_time_limit(240);
+      // Try to allocate enough time to rebuild node grants,
+      // but only if not in 'safe mode' and the maximum execution time is less
+      // than 240 seconds. '0' means unlimited, which is the default when running
+      // php-cli, for example with drush.
+      if (!ini_get('safe_mode') && is_numeric($time_limit = ini_get('max_execution_time')) && $time_limit > 0 && $time_limit < 240) {
+         drupal_set_time_limit(240);
+      }
 
       $nids = db_query("SELECT nid FROM {node}")->fetchCol();
       foreach ($nids as $nid) {
