Windows scripts remote management of hundreds of Apple systems

Source: Internet
Author: User
Tags python script

Problem

Today's colleague's ad account is frequently locked, and the log on the DC shows the authentication failure originating from the wireless network Ise, and the log of the ISE server shows an ad password error for an IP device.

I put the wireless AP in the range, the MAC address of the device to colleagues, the problem came, he turned for half an hour, Leng can't find the corresponding device, and no one reported that the network is not connected. This is embarrassing.

Ideas

How to find the corresponding device, because the wireless network ad authentication failed, the DHCP server does not have any records. Many people turn on WiFi and wired network at the same time, maybe I can find the address of the wireless network card through the wired network.

Beans think of a stupid way, first through the MAC address can determine that this is an Apple network card, then I remotely connect to all the Apple system to query the corresponding network card should be possible to obtain this address.

Do it when you think about it.

Purely practiced hand, I tried it with Python and PowerShell.

Python Script

Python I've written a program that mimics the fabric that can be remotely manipulated, uploaded, and downloaded from multiple Linux or OSX machines. Basically is to call threading, paramiko,queue several modules.

#!/usr/bin/env python#-*-coding:utf-8-*-# Author Yuan Li "" "This program simulates fabric, remote bulk SSH connection, can perform download, upload and shell command execution. Remote command execution, using the thread pool technology, because the execution time is relatively small, and the thread itself execution time accounted for a large proportion; for download and upload, because itself is a time-consuming operation, so each connection uses thread creation and destruction alone, because the time is longer, the thread time can be ignored "" "Import threadingimport queueimport timeimport paramikoimport os# Find relative path Parent_path = Os.path.abspath (os.pardir) db_ Path=os.path.join (Parent_path, ' db ') #一个管理类, the basic idea is to populate the queue (Task pool) with the tasks and related parameters, and then create a process pool, in which the process loops through the contents of the task pool, any content that executes it, Until all tasks are fully implemented.        Class Workmanager (object): #构造函数 def __init__ (self,cmd,username,password,work_num=1000,thread_num=2,): "" " :p Aram cmd: remote command:p Aram Username: User name:p aram Password: password:p aram Work_num: Task Pool (queue size):p ARA        M Thread_num: Thread pool Size "" "Self.cmd=cmd self.work_num=work_num Self.thread_num=thread_num Self.queue=queue. Queue () self.threads=[] Self.init_task (Work_num,cmd,username,password) Self.init_threadpool (thread_nu m) #初始化任务池 def init_task (self,num,inp, Username,password): For I in range (num): Self.add_job (Do_job,i,inp,username,password) #添加任务到任务池 D  EF Add_job (Self,job,*args): #填充任务到任务池, each task is a Ganso (task, parameter list) Self.queue.put ((Job,list (args))) #初始化线程池 def Init_threadpool (self,num): For I in range (num): Self.threads.append (Work (self.queue)) #等待挂起主线程 de F Wait_allcomplete (self): for item in Self.threads:if item.isalive (): Item.join () #线程类, each The thread loops through the task pool and takes the task class work (threading. Thread): Def __init__ (Self,que): Super (Work, self). __init__ () Self.queue=que Self.start () def R Un (self): while True:try: #当任务池为空的时候, force error, exit Do,args=self.queue.get (block                =false) # Print (Do,args) do (args[0],args[1],args[2],args[3]) #确保队列里面的任务都完成了 Self.queue.task_done () except:break# initialization of a host group, tested with the hosts=[' anoble-ise ', ' BBerry-ise ', ' blackbr-ise ', ' jlau-ise ', ' kwood-ise ', ' marwa-ise ', ' smaroo-ise ', ' psekarwin-ise ', ' spare2-ise ']# Remotely connect ssh and execute the command def do_job (Args,inp,username,password): "" ":p the index of the Aram args:hosts list:p Aram INP: remote command:p Aram Usern Ame: User name:p aram Password: password: return: "" "# Time.sleep (0.1) ssh = Paramiko. Sshclient () Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) Ssh.connect (Hosts[args], username, password) # Execute command Test stdin, stdout, stderr = Ssh.exec_comma nd (INP) for line in Stdout.readlines (): Print (Line.strip ()) Print (("\x1b[5;19;32m%s \x1b[0m"% Hosts[args]) . Center (+, ' * ')) print ("\ n") #下载测试def Download (args,user,pwd,remote,local): "":p the index of the Aram args:hosts list:p Aram  INP: remote command:p Aram Username: User name:p aram Password: password: return: "" Try: # print (Hosts[args]) T = Paramiko. Transport ((hosts[args],22)) T.connect (Username=user, password=pwd) sftp = Paramiko.      Sftpclient.from_transport (t)  # remotepath= '/tmp/test2 ' if not os.path.isdir (local): Os.makedirs (local) remotepath=remote Localpath=os.path.join (Local,hosts[args]) sftp.get (RemotePath, LocalPath) print ("Download file succeeded from%s"% Hosts[args        ]) except Exception as Ex:print ("Download file failed from%s"%hosts[args]) # Upload test def upload (args,user,pwd,remote,local): try: # print (Hosts[args]) T = Paramiko. Transport ((Hosts[args],)) T.connect (Username=user, password=pwd) sftp = Paramiko. Sftpclient.from_transport (t) # remotepath= '/tmp/test2 ' remotepath=remote localpath=local # loc    Alpath= ' C:/temp/aaa.txt ' Sftp.put (LocalPath, RemotePath) print (' Upload file to%s success '% Hosts[args]) t.close () Except Exception as Ex:print (' upload file to%s failed '%hosts[args]) #选择主机组def hostinfo (): Global hosts print ("host groups available for selection include: ") from OS import listdir from Os.path import isfile, join # MYPATH=OS.GETCWD () Onlyfiles = [F-F in listdi R(Db_path) if Isfile (Join (Db_path, F))] Print (onlyfiles) for file in Onlyfiles:file_path=os.path.join (Db_path           , file) with open (File_path, ' R ') as Fp:print (("\x1b[5;19;32m%s host list \x1b[0m"%file). Center (40, ' * ')) For Fp:print (Line.strip ()) name=input ("Select the host group name you want to manipulate (hostgroup1,hostgroup2,hostgroup3.)  ") if name in onlyfiles:hosts=[] File_path=os.path.join (db_path,name) with open (File_path, ' R ') as Fp:for line in Fp:hosts.append (Line.strip ()) Else:print ("The host group does not exist") username= "" PASSW Ord= "" #入口文件def Display (): Global Hosts,username,password msg= "" "Welcome to the Fabric emulator, you can do the following 1. Display host group 2. Batch execution of remote life 3. Batch upload 4. Bulk Download 5. Enter the Administrator account 6. Exit "" "" "" "" "" "" "1. Select host Group 2. List the current host MSG2 3. Return to the previous level of the Directory" "" While Tru                E:print (msg) inpt=input ("Please enter Options") #输出主机组的相关信息 if inpt== ' 1 ': While True:          Print (MSG2)      Opt=input ("Please enter Options") if opt== ' 1 ': Hostinfo () elif opt== ' 2 ': For item on Hosts:print (item) elif opt== ' 3 ': Break Else:pri            NT ("illegal input") #远程批量操作 elif inpt== ' 2 ': # username=input ("username") # password=input ("password")                    If not username:print ("Please configure login account information first") Else:while True:                        INP = input ("Input instruction (Q return to parent directory) \n>>>") if InP = = ' Q ': Break if not INP: Print ("Cannot enter null command") Else:start = Time.time () #                        Specify the command, user name, password, size of the task pool (queue), and number of threads) Work_manager = Workmanager (Inp,username,password, Len (hosts), 20) Work_manager.wait_allcomplete () end = Time.time () print ("Cost time is%s"% (enD-start)) #创建批量上传的多线程 elif inpt== ' 3 ': If not username:print ("Please configure login account information First")                Else:remote_path=input ("Remote Path") local_path=input ("Current path") threads = [] For item in range (LEN (hosts)): T = Threading.                    Thread (Target=upload, args= (Item,username,password,remote_path,local_path)) T.start ()             Threads.append (t) for T in Threads:t.join () #创建批量下载的多线程 elif inpt== ' 4 ': If not username:print ("Please configure login account information First") Else:remote_path = input ("Remote file path                    Local_path = input ("Current folder Path") threads=[] for item in range (LEN (hosts)): t = Threading.                    Thread (Target=download, args= (Item,username,password,remote_path,local_path)) T.start ()               Threads.append (t) For T in Threads:t.join () elif inpt== ' 5 ': username = input ("username") passwo RD = input ("password") elif inpt== ' 6 ': Exit ("Exit program") Else:print ("Invalid input, please retry") if __name__ = = ' _ _main__ ': Display ()

Running up the interface is probably like this

PowerShell Script

Then it was purely boring, and I realized it once with PowerShell. PowerShell is primarily connected with third-party module POSH-SSH. This module itself does not provide multi-threaded function, here lazy, beans also useless runspace (multithreading), also did not write exception handling, want to see whether work. So when he connects to the session it's not a concurrent operation, it takes about 10 minutes to set up an SSH session with hundreds of Apple clients, which is much slower than the Python script above.

#先找到所有的苹果系统, exclude ping $sydmac=get-adcomputer-filter {operatingsystem-like ' *mac* '}-properties ipv4address | Where-object {$_.ipv4address-notlike '} $sydmac | Select-expand Dnshostname | Invoke-parallel-scriptblock {test-connection-computername "$_"-count 1-erroraction silentlycontinue-errorvariable Err | Select IPv4Address, @{n= ' DNS '; E={[system.net.dns]::gethostentry ($_.ipv4address). hostname}}-throttle 20 | Select-expandproperty dns| Out-file C:\TEMP\MAC.TXT$LIST=GC C:\temp\mac.txtImport-Module posh-ssh# password account $username = "Administrator" $ Securestringpwd = Convertto-securestring-asplaintext "111222333"-force$creds = New-object System.management.automation.pscredential-argumentlist $username, $SECURESTRINGPWD # The loop here is very low and slow, And each client establishes a session separately, later has the space to change the queue +runspace the multithreading to try the foreach ($line in $list) {new-sshsession-computername $line-credential ( Get-credential $creds)-acceptkey} $sessions =get-sshsessionfor ($i =0; $i-lt $sessions. Length; $i + +) {Invoke-sshcommand-command ' ifconfig | greP ether '-sessionid $i-erroraction silentlycontinue} ' 

The script above works, but the code quality is a bit less, then there is time to optimize.

Windows scripts remote management of hundreds of Apple systems

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.