Python script to check ssh login on multiple hosts against a common password

Below python script can be used to check ssh login on multiple hosts against a common password and print the output to different files based on status. It prompts user to enter the password and check it against all the hostname in the input_file. To speed up the process, I’m using multithreading module which run the jobs in parallel to accomplish the task faster. This script works with Python3.5 version

#!/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")
Advertisements

Install modules in virtualenv for different Python versions(using pip)

If you work with different python versions in virtual environment, you might have noticed that the module installed for a particular python version is not recognized in different python version.

For example, I have 2 python versions in my host.

(virtualenv) [root@machine1 ~]# python -V
Python 2.7.5
(virtualenv) [root@machine1 ~]# python3 -V
Python 3.5.0

I was trying to run the script hack.py and it given an error saying the module not found.

(virtualenv) [root@machine1 script_folder]# python3 hack.py
Traceback (most recent call last):
File "hack.py", line 3, in <module>
import paramiko, multiprocessing
ImportError: No module named 'paramiko'

 

I have installed the module by simply issuing the command pip install

(virtualenv) [root@machine1 script_folder]# pip install paramiko
Collecting paramiko
Using cached paramiko-2.2.1-py2.py3-none-any.whl
Collecting cryptography>=1.1 (from paramiko)
Using cached cryptography-2.0.3-cp27-cp27mu-manylinux1_x86_64.whl
Collecting bcrypt>=3.1.3 (from paramiko)
Using cached bcrypt-3.1.3-cp27-cp27mu-manylinux1_x86_64.whl
Collecting pyasn1>=0.1.7 (from paramiko)
Using cached pyasn1-0.3.2-py2.py3-none-any.whl
Collecting pynacl>=1.0.1 (from paramiko)
Using cached PyNaCl-1.1.2-cp27-cp27mu-manylinux1_x86_64.whl
Collecting idna>=2.1 (from cryptography>=1.1->paramiko)
Using cached idna-2.6-py2.py3-none-any.whl
Collecting six>=1.4.1 (from cryptography>=1.1->paramiko)
Using cached six-1.10.0-py2.py3-none-any.whl
Collecting ipaddress (from cryptography>=1.1->paramiko)
Using cached ipaddress-1.0.18-py2-none-any.whl
Collecting asn1crypto>=0.21.0 (from cryptography>=1.1->paramiko)
Using cached asn1crypto-0.22.0-py2.py3-none-any.whl
Collecting enum34 (from cryptography>=1.1->paramiko)
Using cached enum34-1.1.6-py2-none-any.whl
Collecting cffi>=1.7 (from cryptography>=1.1->paramiko)
Using cached cffi-1.10.0-cp27-cp27mu-manylinux1_x86_64.whl
Collecting pycparser (from cffi>=1.7->cryptography>=1.1->paramiko)
Installing collected packages: idna, six, ipaddress, asn1crypto, enum34, pycparser, cffi, cryptography, bcrypt, pyasn1, pynacl, paramiko
Successfully installed asn1crypto-0.22.0 bcrypt-3.1.3 cffi-1.10.0 cryptography-2.0.3 enum34-1.1.6 idna-2.6 ipaddress-1.0.18 paramiko-2.2.1 pyasn1-0.3.2 pycparser-2.18 pynacl-1.1.2 six-1.10.0

Notice that the module just installed is applicable only to the python version 2.7 and it never works on python3

(virtualenv) [root@machine1 script_folder]# python3 hack.py
Traceback (most recent call last):
File "hack.py", line 3, in <module>
import paramiko, multiprocessing
ImportError: No module named 'paramiko'

Hence, we need to re-install the module in python3 as well using the command below

/Python_location/python3 /pip_location/pip install Module_Name
(virtualenv) [root@machine1 script_folder]# /bin/python3 /bin/pip install paramiko
Collecting paramiko
Using cached paramiko-2.2.1-py2.py3-none-any.whl
Collecting pynacl>=1.0.1 (from paramiko)
Downloading PyNaCl-1.1.2-cp35-cp35m-manylinux1_x86_64.whl (536kB)
100% |████████████████████████████████| 542kB 76kB/s
Collecting cryptography>=1.1 (from paramiko)
Downloading cryptography-2.0.3-cp35-cp35m-manylinux1_x86_64.whl (2.2MB)
100% |████████████████████████████████| 2.2MB 56kB/s
Collecting bcrypt>=3.1.3 (from paramiko)
Downloading bcrypt-3.1.3-cp35-cp35m-manylinux1_x86_64.whl (54kB)
100% |████████████████████████████████| 61kB 140kB/s
Collecting pyasn1>=0.1.7 (from paramiko)
Using cached pyasn1-0.3.2-py2.py3-none-any.whl
Collecting cffi>=1.4.1 (from pynacl>=1.0.1->paramiko)
Downloading cffi-1.10.0-cp35-cp35m-manylinux1_x86_64.whl (406kB)
100% |████████████████████████████████| 409kB 57kB/s
Collecting six (from pynacl>=1.0.1->paramiko)
Using cached six-1.10.0-py2.py3-none-any.whl
Collecting asn1crypto>=0.21.0 (from cryptography>=1.1->paramiko)
Using cached asn1crypto-0.22.0-py2.py3-none-any.whl
Collecting idna>=2.1 (from cryptography>=1.1->paramiko)
Using cached idna-2.6-py2.py3-none-any.whl
Collecting pycparser (from cffi>=1.4.1->pynacl>=1.0.1->paramiko)
Installing collected packages: pycparser, cffi, six, pynacl, asn1crypto, idna, cryptography, bcrypt, pyasn1, paramiko
Successfully installed asn1crypto-0.22.0 bcrypt-3.1.3 cffi-1.10.0 cryptography-2.0.3 idna-2.6 paramiko-2.2.1 pyasn1-0.3.2 pycparser-2.18 pynacl-1.1.2 six-1.10.0

Now, modules imported successfully

(virtualenv) [root@machine1 script_folder]# python3 hack.py
machine is under control now

Enjoy 🙂

Connect to serial console from Linux command line

The easiest way to connect to a serial console from Linux command line is using the screen command. In my example below, I will show you how to connect to a serial console of a server using the serial to usb cable.

[root@test ~]# screen /dev/ttyUSB0
******************************************
 Connected to *******
******************************************

Enjoy 🙂

Rename a host in BackupPC

Follow the below steps to rename a host in BackupPC.
1. Stop BackupPC service :

service backuppc stop

2. Login to the configuration folder

cd /etc/BackupPC

2. Change the host file to the corresponding one :

vi hosts

*change old_host to new_host*

3. Rename the pl file in pc folder :

cd pc

mv old_host.pl new_host.pl

4. Make the changes in the backup location (I assume your backup is storing in the location /backup):

cd /backup/filesystem/pc/

mv old_host new_host

5.Start Backuppc service:

service backuppc start

6. Login to the backuppc console and make sure that the changes are replicated there.

 

Enjoy 🙂

Update the host entry of a user in MySQL

First of all find all the users in your database having permissions.

mysql> select user,host from mysql.user;

If you want to see their permissions,

mysql> show grants for 'root'@'localhost';

Now you want to change the host part of a user. You can issue the below command :

mysql> UPDATE mysql.user SET host = 'New_IP' WHERE host = 'Old_IP' AND user = 'user_you_want_to_change';
mysql> flush privileges;

Very easy 🙂