5

I am working with remote machine. I had to ssh everytime i need verification of file update time and there are multiple scripts which will do ssh to the remote machine. I look over internet but couldn't find according to my requirements.

I am trying to find a python script which uses ssh and the password is also in the script because my python scripts will check every 5 minutes the file modification times and i cannot enter password everytime the script execute. I tried these codes from SO and internet but couldn't fulfil my need. Establish ssh session by giving password using script in python

How to execute a process remotely using python

Also I enter into one remote machine through ssh simply.then I am trying to ssh but via python script to another remote machine cox this python script also include code to check the modification time of different files.. mean i already ssh to one remote machine and then i want to run some python scripts from there which checks file modification time of files on another remote machine. Is there a simple way to ssh remote machine along with password in python script. . I would be grateful.

6
  • why not setup [ssh keys ] (thegeekstuff.com/2008/11/…) . You don't need a password then? Commented Aug 10, 2017 at 14:05
  • @Macintosh_89 but i am running some scripts from one remote machine on another. mean i already ssh to one remote machine and then i am running some python scripts which checks file modification time of files on another remote machine. that why i am looking for simple script which include ssh to remote machine along with password option in it. Commented Aug 10, 2017 at 14:09
  • @Macintosh_89 but i will give it a try to your suggestion. Commented Aug 10, 2017 at 14:10
  • take a look at paramiko and sshpass. Commented Aug 10, 2017 at 14:11
  • 1
    you can also use subprocess.call() in combination with the bash command expect check stackoverflow.com/questions/16928004/… and stackoverflow.com/questions/4780893/… Commented Aug 10, 2017 at 14:14

2 Answers 2

3

If you want to try paramiko module. Here is a sample working python script.

import paramiko

def start_connection():
    u_name = 'root'
    pswd = ''
    port = 22
    r_ip = '198.x.x.x'
    sec_key = '/mycert.ppk'

    myconn = paramiko.SSHClient()
    myconn.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    my_rsa_key = paramiko.RSAKey.from_private_key_file(sec_key)

    session = myconn.connect(r_ip, username =u_name, password=pswd, port=port,pkey=my_rsa_key)

    remote_cmd = 'ifconfig'
    (stdin, stdout, stderr) = myconn.exec_command(remote_cmd)
    print("{}".format(stdout.read()))
    print("{}".format(type(myconn)))
    print("Options available to deal with the connectios are many like\n{}".format(dir(myconn)))
    myconn.close()


if __name__ == '__main__':
    start_connection()
Sign up to request clarification or add additional context in comments.

9 Comments

ssh is a secure protocol, which take key pairs to make connection secure, Check out this. sec_key='/mycert.ppk' is an absolute path to my private key. You/machine should be having one.
Thanks, i will give it a try. hopefully it will solve my problem. i am new to ssh and remote machine connections. thats why I ask
no worries, you can ask me if script is not yet clear to you.
this paramiko should also be installed on remote machine?. .is there any other way to do it. i generate key pairs but i am avoiding to install paramiko on remote machine. .
I installed the paramiko on remote machine, then i receive that enum module is not define. i installed that, ,now it shows that "ImportError: No module named pyasn1.type.univ ". Any idea how to deal with this error
|
0

Adding my program as well here which relies on the user password and displays the status on different output files.

#!/bin/python3
import threading, time, paramiko, socket, getpass
from queue import Queue
locke1 = threading.Lock()
q = Queue()

#Check the login
def check_hostname(host_name, pw_r):
    with locke1:
        print ("Checking hostname :"+str(host_name)+" with " + threading.current_thread().name)
        file_output = open('output_file','a')
        file_success = open('success_file','a')
        file_failed = open('failed_file','a')
        file_error = open('error_file','a')
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        try:
          ssh.connect(host_name, username='root', password=pw_r, timeout=5)
          #print ("Success")
          file_success.write(str(host_name+"\n"))
          file_success.close()
          file_output.write("success: "+str(host_name+"\n"))
          file_output.close()

          # printing output if required from remote machine
          #stdin,stdout,stderr = ssh.exec_command("hostname&&uptime")
          #for line in stdout.readlines():
           # print (line.strip())

        except paramiko.SSHException:
                # print ("error")
                file_failed.write(str(host_name+"\n"))
                file_failed.close()
                file_output.write("failed: "+str(host_name+"\n"))
                file_output.close()
                #quit()
        except paramiko.ssh_exception.NoValidConnectionsError:
                #print ("might be windows------------")
                file_output.write("failed: " + str(host_name + "\n"))
                file_output.close()
                file_failed.write(str(host_name+"\n"))
                file_failed.close()
                #quit()
        except socket.gaierror:
          #print ("wrong hostname/dns************")
          file_output.write("error: "+str(host_name+"\n"))
          file_output.close()
          file_error.write(str(host_name + "\n"))
          file_error.close()

        except socket.timeout:
           #print ("No Ping %%%%%%%%%%%%")
           file_output.write("error: "+str(host_name+"\n"))
           file_output.close()
           file_error.write(str(host_name + "\n"))
           file_error.close()

        ssh.close()


def performer1():
    while True:
        hostname_value = q.get()
        check_hostname(hostname_value,pw_sent)
        q.task_done()

if __name__ == '__main__':

    print ("This script checks all the hostnames in the input_file with your standard password and write the outputs in below files: \n1.file_output\n2.file_success \n3.file_failed \n4.file_error \n")

    f = open('output_file', 'w')
    f.write("-------Output of all hosts-------\n")
    f.close()
    f = open('success_file', 'w')
    f.write("-------Success hosts-------\n")
    f.close()
    f = open('failed_file', 'w')
    f.write("-------Failed hosts-------\n")
    f.close()
    f = open('error_file', 'w')
    f.write("-------Hosts with error-------\n")
    f.close()

    with open("input_file") as f:
        hostname1 = f.read().splitlines()

#Read the standard password from the user
    pw_sent=getpass.getpass("Enter the Password:")
    start_time1 = time.time()

    for i in hostname1:
        q.put(i)
    #print ("all the hostname : "+str(list(q.queue)))
    for no_of_threads in range(10):
        t = threading.Thread(target=performer1)
        t.daemon=True
        t.start()

    q.join()
    print ("Check output files for results")
    print ("completed task in" + str(time.time()-start_time1) + "seconds")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.