1

I want to write a python script to ssh remote machines and run command netstat -antp | grep httpd run this script in Cron job.

Here I'm grepping for httpd service and check the port no (say 80). Only one of the remote machine can have 80 rest should have different port no like 8888 or 8080.

list of remote machine I want to take as argument while running the python script.

Below is my code snippet:

import subprocess
import sys

machine_list= sys.argv[1]

for machine in machine_list:
    command = "sudo netstat -antp | grep httpd"
    ssh = subprocess.Popen(["ssh", "%s" % machine, command],
                            shell=False,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)
    result = ssh.stdout.readlines()

Problem is everytime I run it asks me for password of remote machine. I cannot give password manually if running in cron. What can be done?

Jakuje
  • 24,773
  • 12
  • 69
  • 75
kittu deopa
  • 79
  • 2
  • 2
  • 12

1 Answers1

0

If you log in as the user that's running the cron task, you should be able to set up ssh key based logins.

Firstly, you'll need the ssh public and private keys, if you've not already generated them:

ssh-keygen -t rsa -b 2048

Then, you can use ssh-copy-id:

ssh-copy-id user@hostname

This will put the public key you generated with ssh-keygen into the authorized_keys file of the remote user on 'hostname'. It will then only prompt you for the password of the key (if you set one) or not if you're using ssh-agent.

It may also be useful to look at the paramiko module, which does ssh connections. http://www.paramiko.org/

You're using sudo to run netstat, which may also prompt you for a password. With what you're running in the posted example, you should get the answer you want from netstat -antp without sudo

Simon Fraser
  • 2,758
  • 18
  • 25