Почему удаленная команда SSH получает меньше переменных среды, чем при запуске вручную? [закрыто]

StackOverflow https://stackoverflow.com/questions/216202

  •  03-07-2019
  •  | 
  •  

Вопрос

У меня есть команда, которая отлично работает, если я запускаю ssh на машине и запускаю ее, но не удается выполнить ее с помощью удаленной команды ssh, например:

ssh user@IP <command>

Сравнение результатов "env" с помощью обоих методов Resutls в разных средах. Когда я вручную захожу на компьютер и запускаю env, я получаю гораздо больше переменных окружения, чем при запуске:

ssh user@IP "env"

Есть идеи почему?

Это было полезно?

Решение

Существуют разные типы оболочек. Оболочка выполнения команд SSH - это неинтерактивная оболочка, тогда как обычная оболочка является либо оболочкой входа в систему, либо интерактивной оболочкой. Описание следует из man bash:

       A  login  shell  is  one whose first character of argument
       zero is a -, or one started with the --login option.

       An interactive shell is  one  started  without  non-option
       arguments  and  without the -c option whose standard input
       and error are both connected to terminals  (as  determined
       by  isatty(3)), or one started with the -i option.  PS1 is
       set and $- includes i if bash is interactive,  allowing  a
       shell script or a startup file to test this state.

       The  following  paragraphs  describe how bash executes its
       startup files.  If any of the files exist  but  cannot  be
       read,  bash reports an error.  Tildes are expanded in file
       names as described below  under  Tilde  Expansion  in  the
       EXPANSION section.

       When  bash is invoked as an interactive login shell, or as
       a non-interactive shell with the --login option, it  first
       reads and executes commands from the file /etc/profile, if
       that file exists.  After reading that file, it  looks  for
       ~/.bash_profile,  ~/.bash_login,  and  ~/.profile, in that
       order, and reads and executes commands from the first  one
       that  exists  and is readable.  The --noprofile option may
       be used when the shell is started to inhibit  this  behav­
       ior.

       When a login shell exits, bash reads and executes commands
       from the file ~/.bash_logout, if it exists.

       When an interactive shell that is not  a  login  shell  is
       started,  bash reads and executes commands from ~/.bashrc,
       if that file exists.  This may be inhibited by  using  the
       --norc  option.   The --rcfile file option will force bash
       to  read  and  execute  commands  from  file  instead   of
       ~/.bashrc.

       When  bash  is  started  non-interactively, to run a shell
       script, for example, it looks for the variable BASH_ENV in
       the  environment,  expands  its value if it appears there,
       and uses the expanded value as the name of a file to  read
       and  execute.   Bash  behaves  as if the following command
       were executed:
              if [ -n "$BASH_ENV" ]; then . "$BASH_ENV"; fi
       but the value of the PATH variable is not used  to  search
       for the file name.

Другие советы

Как насчет поиска профиля перед запуском команды?

ssh user @ host & source / etc / profile; /path/script.sh"

Возможно, вам будет лучше изменить это значение на ~ / .bash_profile , ~ / .bashrc или на что угодно.

(как здесь (linuxquestions.org) )

Среда оболочки не загружается при запуске удаленной команды ssh. Вы можете редактировать файл окружения ssh:

vi ~/.ssh/environment

Его формат:

VAR1=VALUE1
VAR2=VALUE2

Кроме того, проверьте конфигурацию sshd для параметра PermitUserEnvironment = yes.

У меня была похожая проблема, но в итоге я узнал, что ~ / .bashrc - это все, что мне нужно.

Однако в Ubuntu мне пришлось прокомментировать строку, которая останавливает обработку ~ / .bashrc:

#If not running interactively, don't do anything
[ -z "$PS1" ] && return

Я нашел простое решение этой проблемы, чтобы добавить   источник / etc / profile в начало файла script.sh, который я пытался запустить в целевой системе. В этих системах это привело к тому, что переменные окружения, которые требовались для script.sh, были настроены так, как если бы они запускались из оболочки входа в систему.

В одном из предыдущих ответов было предложено использовать ~ / .bashr_profile и т. д. Я не тратил много времени на это, но проблема в том, что если вы используете ssh для другого пользователя в целевой системе, а не для оболочки исходной системы, из которой вы вошли, мне показалось, что это вызывает пользователя исходной системы. имя, которое будет использоваться для ~.

Просто экспортируйте переменные среды, которые вы хотите, перед проверкой неинтерактивной оболочки в ~ / .bashrc.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top