Setting Environment Variables during SSH2 Connection

Aug 20, 2024 · 1 min read · 176 Words · -Views -Comments · Programming
Ssh2 🇨🇳 阅读中文版
Read with AI

Choose an AI assistant

ChatGPT Open in a new tab with the article link and prompt
Claude Copy the prompt, then open Claude

Open Claude
Trouble reading the article?

If the prompt is missing, copy the full prompt below into your AI assistant. If the AI cannot read the article, paste the visible passage you want to discuss and add your question.

Can environment variables be set when connecting to a server using the Node.js SSH2 client? After investigation, it was found that it is possible. Just marking it here.

Setting Environment Variables

The code is as follows:

this.conn.shell({
        env: {
          X_LOGIN_IP: '128.1.1.123',
          X_ENVIRONMENT_VARIABLE: "desiredvalue"
        }, term: 'xterm-256color', // term: 'dumb',
        cols: connectOpts.cols, rows: connectOpts.rows,
      }, (err, s) => {
        if (err) {
          console.log('ssh shell error', err);
          throw err;
   }    
})

Limitations

This environment variable setting is restricted by whether the /etc/ssh/sshd_config allows setting specific rule variables. Different systems have different defaults for the allowed environment variable settings.

If you need to allow specific variables, the setting directive is AcceptEnv. The example below supports setting environment variables with the X_ prefix.

https://static.1991421.cn/2024/2024-08-20-160215.jpeg

Default Supported Environment Variables

As mentioned earlier, different systems have different default settings.

  • Ubuntu defaults to AcceptEnv LANG LC_*
  • Debian defaults to AcceptEnv LANG LC_*
  • CentOS9 does not have AcceptEnv set by default, meaning no environment variables can be set.

At the end

That’s all you need to know about setting environment variables on the client side.

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover