1

I am trying to edit the motd, but instead of bash scripts I want to use Python Scripts. It turns out, that Python Scripts do not work with imported libraries.

for example, this would work:

#!/usr/bin/env python3
print("Hello")

However, this does not work:

#!/usr/bin/env python3
import psutil
print(f"Users: {len(psutil.users())}")

When using the command sudo update-motd both scripts work, but when I try to connect via ssh only the upper script works. I have already checked the following settings of ssh:

in /etc/ssh/sshd_config PrintMotd is enabled:

PrintMotd yes

in /etc/pam.d/ssh I have these settings for motd:

session    optional     pam_motd.so  motd=/run/motd.dynamic
session    optional     pam_motd.so noupdate

I am using Ubuntu 18.04.3 LTS x86_64

7
  • Does it work if you use a specific python instead of env? Something like #!/usr/bin/python3? I'm thinking that the default PATH when you connect via ssh is sending you to a different python version because you're using env and that python version doesn't have the necessary packages for some reason.
    – terdon
    Aug 22, 2019 at 16:10
  • @terdon I changed the shebang to #!/usr/bin/python3, but unfortunately that leads to the same result
    – Vulturemox
    Aug 22, 2019 at 16:17
  • How did you install python 3 psutil? is the PYTHONPATH different for root compared to your non-privileged user(s)? Aug 22, 2019 at 16:45
  • @steeldriver I installed psutil with pip3 install psutil. The command python3 -c "import psutil as _; print(_.__path__)" returns the installation path of psutil which is in my home directory: /home/vulturemox/.local/lib/python3.6/site-packages/psutil (running it as sudo returns the same path). Is there a better way to install psutil? When I run echo $PYTHONPATH it returns nothing (regardless of sudo). Should I define PYTHONPATH?
    – Vulturemox
    Aug 22, 2019 at 17:02
  • Right - so there's your problem - motd scripts are run as root. If you'd installed the python3-psutil package then it should work with the default python3 from the repo (assuming you haven't done anything rash like remove the default python3 of course). Aug 22, 2019 at 17:07

1 Answer 1

0

I found the solution myself: The best way to solve this problem is to create a virtualenv (first install it with sudo apt-get install python-virtualenv)

Then initiate it with virtualenv path/to/env

Activate it source path/to/env/bin/activate

Install all dependencies with pip3

Then in the motd files I just changed the shebang to point at the virtualenv

#!path/to/env/bin/python3

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .