0

Below simple scripts, used to list keys in ssh-agent:

list_keys.sh:

#!/bin/bash
ssh-add -l

list_keys.py:

if __name__ == '__main__':
    """
    Creates log
    """
    ...

    print("Start")
    print subprocess.check_output(["/root/list_keys.sh"])

It works well when called directly from the terminal.

$python list_keys.py

The log shows as expected:

Start
2048 SHA256:+gkk***************************nQ .ssh/my_key (RSA)

But when I tried to make it as service, it fails.

Start
Traceback (most recent call last):
  File "/root/list_keys.py", line 43, in <module>
print subprocess.check_output(["/root/list_keys.sh"])
  File "/usr/lib64/python2.7/subprocess.py", line 575, in check_output
raise CalledProcessError(retcode, cmd, output=output)
subprocess
.
CalledProcessError
:
Command '['/root/list_keys.sh']' returned non-zero exit status 2

The service config:

list_keys.service:

[Unit]
Description=List Keys Service
After=multi-user.target
Conflicts=getty@tty1.service

[Service]
Type=simple
ExecStart=/usr/bin/python /root/list_keys.py
StandardInput=tty-force

[Install]
WantedBy=multi-user.target

I'm working on Centos 7. Any clue how to make the list_keys.py as service?

yuwono95
  • 237
  • 3
  • 11
  • Could it be that you need to specify the full path to list_keys.py in the service definition, and to list_keys.sh in the Python file? When you run it in the terminal, does it work if you call it from a different folder? – saintamh Jan 09 '20 at 10:48
  • Edited. Actually the full path is there, I just cut it in post for simplicity. Anyway, it won't print "Start" if the script cannot be found. I think its not about the incorrect path. – yuwono95 Jan 09 '20 at 11:07

2 Answers2

0

You most likely forgot the execution bit on your shell file, easily fixed by:

chmod +x list_keys.sh

The next candidate would be the full path to ssh-add:

/usr/bin/ssh-add
lenik
  • 23,228
  • 4
  • 34
  • 43
0

Turns out the problem is not in the subprocess. When the script called from service, it has a different session than the ones from the terminal. That's why "ssh-add -l" fails because of no ssh-agent established in that session. Added script to establishing ssh-agent in "list_keys.sh" solved my problem.

Reference on how to establish ssh-agent.

The python subprocess has nothing to do with it.

yuwono95
  • 237
  • 3
  • 11