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.

robbin
  • 313
  • 1
  • 5
  • 14
  • why not setup [ssh keys ] (http://www.thegeekstuff.com/2008/11/3-steps-to-perform-ssh-login-without-password-using-ssh-keygen-ssh-copy-id) . You don't need a password then? – Macintosh_89 Aug 10 '17 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. – robbin Aug 10 '17 at 14:09
  • @Macintosh_89 but i will give it a try to your suggestion. – robbin Aug 10 '17 at 14:10
  • take a look at `paramiko` and `sshpass`. –  Aug 10 '17 at 14:11
  • 1
    you can also use `subprocess.call()` in combination with the bash command `expect` check https://stackoverflow.com/questions/16928004/how-to-enter-ssh-password-using-bash and https://stackoverflow.com/questions/4780893/use-expect-in-bash-script-to-provide-password-to-ssh-command#4783182 – alec_djinn Aug 10 '17 at 14:14
  • @alec_djinn you mean using these bash commands in python script? – robbin Aug 10 '17 at 14:30

2 Answers2

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()
Ajay2588
  • 527
  • 3
  • 6
  • 1
    ssh is a secure protocol, which take key pairs to make connection secure, [Check out this](https://www.ssh.com/ssh/protocol/). `sec_key='/mycert.ppk'` is an absolute path to my private key. You/machine should be having one. – Ajay2588 Aug 10 '17 at 14:26
  • 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 – robbin Aug 10 '17 at 14:35
  • no worries, you can ask me if script is not yet clear to you. – Ajay2588 Aug 10 '17 at 15:16
  • 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. . – robbin Aug 10 '17 at 15:52
  • 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 – robbin Aug 10 '17 at 16:44
  • client [your machine], an remote server [machine you want to connect to]. paramiko should be installed in client machine only. In the code snippet above, `r_ip = '198.x.x.x'` replace 198.x.x.x with your remote server's IP. I believe user will be `root`, if not then use the intended username. Things should work fine. Try it out. – Ajay2588 Aug 10 '17 at 17:33
  • since i ssh one remote machine. i installed the paramiko on it. and then i try to use the above mention code until this line " session = myconn.connect(r_ip, username =u_name, password=pswd, port=port,pkey=my_rsa_key)"...................cox i just want to enter into that another remote machine and my script will be executed. ....................................but i got these above mention errors. .and r_ip is the address of current remote machine or the machine in which i want to ssh?. .thanks for guidance. – robbin Aug 10 '17 at 18:37
  • I enter through ssh to one remote machine and from there I want to access another remote machine where I want to know the modification time of different files. . – robbin Aug 10 '17 at 18:55
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/151671/discussion-between-ajay2588-and-robbin). – Ajay2588 Aug 11 '17 at 05:38
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")
Gopu
  • 1,022
  • 2
  • 11
  • 20