1. Use Python to view the status of all hosts in a network segment (3 seconds implementation)
#vim ping.py
Import subprocess
Import threading
def Ping (host):
result = Subprocess.call (
' Ping-c2%s &>/dev/null '% host,
Shell=true
)
if result = = 0:
Print "%s:up"% host
Else
Print "%s:down"% host
if __name__ = = ' __main__ ':
ips = [' 172.40.55.%s '% i for I in range (1, 255)]
For IP in IPs:
t = Threading. Thread (target=ping, args= (IP,))
T.start ()
[[Email protected] Desktop]# python mtping.py
172.40.55.1:up
172.40.55.66:up
172.40.55.6:down
172.40.55.114:up
172.40.55.2:down
172.40.55.3:down
172.40.55.115:up
。。。。。
2. Use SSH for multi-threaded concurrent access (you can create a delete, the password, etc.)
[email protected] ~]# Yum install-y Python-paramiko
#vim allhost.py
Import Getpass
Import OS
Import Paramiko
Import Sys
Import threading
def remote_comm (host, passwd, comm, user= ' root '):
SSH = Paramiko. Sshclient ()
Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ())
Ssh.connect (host, Username=user, PASSWORD=PASSWD)
stdin, stdout, stderr = Ssh.exec_command (comm)
out = Stdout.read ()
Err = Stderr.read ()
If out:
print ' [out]%s:\n%s '% (host, out),
If err:
print ' [error]%s:\n%s '% (host, err),
Ssh.close ()
if __name__ = = ' __main__ ':
If Len (sys.argv)! = 3:
Print "Usage:%s ipfile ' command '"% sys.argv[0]
Sys.exit (1)
If not Os.path.isfile (Sys.argv[1]):
Print "No such file:", Sys.argv[1]
Sys.exit (2)
Ipfile = sys.argv[1]
Command = sys.argv[2]
PWD = Getpass.getpass ()
With open (ipfile) as Fobj:
For line in Fobj:
ip = Line.strip ()
t = Threading. Thread (Target=remote_comm, args= (IP, pwd, command))
T.start ()
#vim Ipaddr.txt
192.168.4.1
192.168.4.2
192.168.4.3
192.168.4.4
[[Email protected] Desktop]# python remote_comm.py ipaddr.txt tedu.cn ' Useradd Bob '
This article is from the "12336621" blog, please be sure to keep this source http://12346621.blog.51cto.com/12336621/1909776
Python utility script