Python Forum
Multithreading with ssh connection
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Multithreading with ssh connection
#1
Hello,

i need help with implementation Queue and maybe Lock in multithreading operation. Code below will print results i want, but i want to return it as object for further operations. if there is option to solve this with multiprocessing please how to apply it to this concrete code.

self.query_sort() ## Returns Dictionary with ip addresses scope {"9" : "192.168.9.0", "192.168.9.1", ....} it's about 400 IP's in 7 different scopes

self.list_result = []

def get_network_data(self, ixx):
        for ix in ixx:
                sshh = SshConnection(ix, self.username, self.password) # Connecting to SSH ix is ip address
            try:
                out1, err1 = sshh.ssh_command("ioreg -c IOPlatformExpertDevice "
                                              "-d 2 | awk '/IOPlatformSerialNumber/'")  # Get computer  serial number
                serial_number = out1[0].strip().split('"')
                out2, err2 = sshh.ssh_command('echo $HOSTNAME') # Get computer name
                station_name = out2[0].strip().split(".")[0]
                new_rec = ix + ":" + serial_number[3] + ":" + station_name
                print(new_rec) # returns "192.168.9.1:DXXXXXXXXXX:MY_NAME"
                self.list_result.append(new_rec) # This will return None because writing to shared memory
            except:
                pass


    def thread_queue(self):
        dict_all = self.query_sort()
        for x in dict_all.values():
            t = threading.Thread(target=self.get_network_data, args=(x,))
            t.start()
Thanks.
Reply
#2
change
                self.list_result.append(new_rec) # This will return None because writing to shared memory
to
                return new_rec
and work with that data outside of the function
In addition, you should handle your exception
Reply
#3
Hi again,

thank you for your swift answer, i have updated code with what you said and result is same as before. You can see i have used list to append new values in loop which differs from what you wrote but it makes no difference result is 'None'. Sad

Any other ideas where i am making mistake?

    def get_network_data(self, ixx):
        list_result = []
        for ix in ixx:
            if ix.startswith("10.172.9."):
                sshh = SshConnection(ix, "apple", "apple")
            else:
                sshh = SshConnection(ix, self.username, self.password)
            try:
                out1, err1 = sshh.ssh_command("ioreg -c IOPlatformExpertDevice "
                                              "-d 2 | awk '/IOPlatformSerialNumber/'")
                serial_number = out1[0].strip().split('"')
                out2, err2 = sshh.ssh_command('echo $HOSTNAME')
                station_name = out2[0].strip().split(".")[0]
                new_rec = ix + ":" + serial_number[3] + ":" + station_name
                # print(new_rec)
                list_result.append(new_rec)
                return list_result
            except (ssh_exception.AuthenticationException,
                    ssh_exception.NoValidConnectionsError,
                    ssh_exception.SSHException,
                    socket.timeout) as err:
                pass


    def thread_queue(self):
        dict_all = self.query_sort()
        for x in dict_all.values():
            t = threading.Thread(target=self.get_network_data, args=(x,))
            t.start()


new_nmap = NmapScan()
list_res = new_nmap.thread_queue() # >>>> Returns None
print(list_res)
for item in list_res:
    print(item) # >>>> TypeError: 'NoneType' object is not iterable
Reply
#4
you load target with the return result, but you don't do anything with it.
How you process the data after you get it returned is up to you
Reply
#5
Is it possible to write example how should i return list out of that function? I am not sure i understand what you mean.
Reply
#6
First of all, since I see self in the argument list for your methods include self, I assume there is a class that this is operating from
(you should provide full listings or at least full classes when posting).
So under the class __init__ method, add a line self.target = None
then modify:
t = threading.Thread(target=self.get_network_data, args=(x,))
# to 
t = threading.Thread(self.target=self.get_network_data, args=(x,))
your data is now in self.target to do with as you please
Reply
#7
Thank you for your response i have resolved it, it took me long enough to see the issue. Dance
One thing still bothers me and it's speed of ssh over paramiko taking too long, when i am sending two separate requests with 3 sec timeouts. 400 computers 77 sec (I don't know if it is bad but i guess it's no good.

def get_network_data(self, ixx, qq):
        """Checking computers for Serial number and name"""
        self.set_result = set()
        qq.put(ixx)
        for ix in ixx:
            if ix.startswith("10.172.9."):
                sshh = SshConnection(ix, "apple", "apple")
            else:
                sshh = SshConnection(ix, self.username, self.password)
            try:
                out1, err1 = sshh.ssh_command("ioreg -c IOPlatformExpertDevice "
                                              "-d 2 | awk '/IOPlatformSerialNumber/'")
                serial_number = out1[0].strip().split('"')
                out2, err2 = sshh.ssh_command('echo $HOSTNAME')
                station_name = out2[0].strip().split(".")[0]
                new_rec = ix + ":" + serial_number[3] + ":" + station_name
                # print(new_rec)
                self.set_result.add(new_rec)
            except (ssh_exception.AuthenticationException,
                    ssh_exception.NoValidConnectionsError,
                    ssh_exception.SSHException,
                    socket.timeout) as err:
                pass
        qq.task_done()



    def thread_queue(self):
        qq = Queue()
        dict_all = self.query_sort()
        for x in dict_all.values():
            t = threading.Thread(self.target=self.get_network_data, args=(x, qq))
            t.start()
        t.join()
        qq.join()
        return self.set_result


new_nmap = NmapScan()
list_res = new_nmap.thread_queue() # >>>> Returns None
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  multithreading Hanyx 4 1,325 Jul-29-2022, 07:28 AM
Last Post: Larz60+
Question Problems with variables in multithreading Wombaz 2 1,326 Mar-08-2022, 03:32 PM
Last Post: Wombaz
  Serial connection connection issue Joni_Engr 15 8,058 Aug-30-2021, 04:46 PM
Last Post: deanhystad
  Multithreading question amadeok 0 1,781 Oct-17-2020, 12:54 PM
Last Post: amadeok
  How can i add multithreading in this example WoodyWoodpecker1 3 2,513 Aug-11-2020, 05:30 PM
Last Post: deanhystad
  matplotlib multithreading catosp 0 2,950 Jul-03-2020, 09:33 AM
Last Post: catosp
  Multithreading dynamically syncronism Rodrigo 0 1,534 Nov-08-2019, 02:33 AM
Last Post: Rodrigo
  Locks in Multithreading Chuonon 0 1,847 Oct-03-2019, 04:16 PM
Last Post: Chuonon
  multithreading issue with output mr_byte31 4 3,201 Sep-11-2019, 12:04 PM
Last Post: stullis
  Multithreading alternative MartinV279 1 2,792 Aug-01-2019, 11:41 PM
Last Post: scidam

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020