I have been studying python recently and feel very good, especially for Batch/concurrent processing. It is very convenient to implement and much more convenient than shell. I just learned python for a month and keep a record here. The following is a piece of code. More suggestions/comments ~ (Qq group exchange: 24967504)
Requirement: View/compare the status of online servers in batches, such as uptime, df-h, and MD5sum files. This command is intended to be run through parameter passing and password interactive input (three times without exit ). Further improvements ~~
#-*-Coding: UTF-8 -*-
#! /Usr/bin/python
Import paramiko
Import threading
Def ssh2 (ip, username, passwd, cmd ):
Try:
Ssh = paramiko. SSHClient ()
Ssh. set_missing_host_key_policy (paramiko. AutoAddPolicy ())
Ssh. connect (ip, 22, username, passwd, timeout = 5)
For m in cmd:
Stdin, stdout, stderr = ssh.exe c_command (m)
Stdin. write ("Y ")
Out = stdout. readlines ()
For o in out:
Print o,
Print '[OK] % s' % (ip ),
Print '============================================== ========================================='
Ssh. close ()
Except t:
Print '[Error] % s' % (ip ),
Print '============================================== ========================================='
Def main ():
Cmd = ['uptime'] # Run the command
Username = "root"
Passwd = "password"
Threads = [4]
F = file('list.txt ') # ip address list
While True:
Ip = f. readline ()
If len (ip) = 0:
Break
A = threading. Thread (target = ssh2, args = (ip, username, passwd, cmd ))
A. start ()
F. close ()
If _ name _ = '_ main __':
Main ()
Execution result:
[Root @ bw-vm-soft ~] # Python ssh2.py
13:31:28 up 514 days, 1 user, load average: 10.27, 9.44, 9.03
[OK] 192.168.13.116
========================================================== ======================================
13:31:28 up 514 days, 1 user, load average: 5.99, 6.05, 6.46
[OK] 192.168.13.117