python自動化指令碼例項100條-自動化運維基礎例項解析-Python批量登入到伺服器執行任務...

weixin_37988176發表於2020-11-01

開發背景:

根據資訊系統安全等級保護的要求,需要對IDC所有資料庫伺服器進行安全檢查,以確認伺服器的安全設定是否符合等級保護要求,需要在所有資料庫伺服器上執行以下命令:

wget http://10.4.4.140/tools/check.sh

bash check.sh

對於目前現狀,我們總共目前約有mysql資料庫約60臺左右,加上oracle資料庫會更多,如果通過單一的登入到每個資料庫伺服器執行,效率是非常低的,所以寫了一個批量執行的Python指令碼。該指令碼會讀取一個定義好的伺服器列表和命令列表,然後利用了python的多程式特性,每個伺服器一個獨立程式,自動登入到對應的伺服器,執行相應的指令碼。登入認證方式包括密碼登入和金鑰登入,如果定義了金鑰,則指令碼會使用金鑰登入,否則則使用密碼登入。該指令碼比較通用,在自動化監控和運維過程中比較實用,下面將對指令碼做簡單的分析。

程式碼解析:

該指令碼共有兩個檔案,linux_batch_command.py和linux_servers.list。linux_batch_command.py用於執行自動登入和執行指令碼。linux_servers.list用於定義主機列表。

linux_batch_command.py程式碼如下:需要執行的命令定義在cmds="’" ’"’裡面,需要執行多個命令用,分隔。timeout用於定義登入伺服器和執行指令碼的超時時間,執行時間比較長的話該值請修改的比較大些。

#!//bin/env python

#ssh_cmd_ver2.py

#coding:utf-8

import pexpect

import os, sys, string, time, datetime, traceback;

from multiprocessing import Process;

cmds= '''cd /tmp && wget http://10.4.4.140/tools/check.sh && bash check.sh'''

def ssh_cmd(ip,port,user,keyfile,passwd,cmd):

if keyfile <> '':

ssh = pexpect.spawn('ssh -p%s -i %s %s@%s "%s"' % (port,keyfile, user, ip, cmd))

try:

i = ssh.expect(["Enter passphrase for key '"+keyfile+"': ", 'continue connecting (yes/no)?'],timeout=60)

if i == 0 :

ssh.sendline(passwd)

r = ssh.read()

elif i == 1:

ssh.sendline('yes ')

ssh.expect("Enter passphrase for key '"+keyfile+"': ")

ssh.sendline(passwd)

r = ssh.read()

except pexpect.EOF:

ssh.close()

r=ip+":EOF"

except pexpect.TIMEOUT:

#ssh.close()

r="ip:TIMEOUT"

return r

else:

ssh = pexpect.spawn('ssh -p%s %s@%s "%s"' % (port, user, ip, cmd))

try:

i = ssh.expect(['password: ', 'continue connecting (yes/no)?'],timeout=60)

if i == 0 :

ssh.sendline(passwd)

r = ssh.read()

elif i == 1:

ssh.sendline('yes ')

ssh.expect('password: ')

ssh.sendline(passwd)

r = ssh.read()

except pexpect.EOF:

ssh.close()

r="EOF"

except pexpect.TIMEOUT:

#ssh.close()

r="TIMEOUT"

return r

def job_task(ip,port,user,keyfile,passwd):

for cmd in cmds.split(","):

r=ssh_cmd(ip,port,user,keyfile,passwd,cmd)

print r

def main():

print("%s: controller started." % (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()),));

hosts = open('./linux_servers.list');

plist = []

for host in hosts:

if host:

ip,port,user,keyfile,passwd = host.split(":")

p = Process(target = job_task, args = (ip,port,user,keyfile,passwd))

plist.append(p)

#print plist

p.start();

for p in plist:

p.join();

print("%s: controller finished." % (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()),))

if __name__=='__main__':

main()

linux_servers.list檔案內容如下:

該檔案裡面定義需要登入執行命令的伺服器,示例如下,每個伺服器以單獨行寫在檔案裡面,第一行為密碼登入的伺服器格式示例,第二行為密碼方式登入的伺服器格式示例,定義好伺服器後執行指令碼,指令碼會根據定義的格式自動選擇登入方式

[root@hadoop-master servers]# cat linux_servers.list

10.0.2.100:22:ruzuojun:/home/ruzuojun/.ssh/id_rsa:keypasswd

10.0.2.200:22:root::passwd

執行指令碼,檢視執行結果:

執行命令後,在終端會返回每個機器的執行輸出結果,如果某個主機執行有異常則會輸出EOF,執行超時則會資料TIMEOUT.

[root@hadoop-master servers]# ./linux_batch_command.py

******************** 檢查是否開啟X-Window系統 *************************************************

[ OK ] 檢查通過

% Total % Received % Xferd Average Speed Time Time Time Current

Dload Upload Total Spent Left Speed

0 0 0 0 0 0 0 0 –:–:– –:–:– –:–:– 0

******************** 檢查系統關機熱鍵是否啟用 ***********************************

[ FAILED ] 系統關機熱鍵已啟用

% Total % Received % Xferd Average Speed Time Time Time Current

Dload Upload Total Spent Left Speed

0 0 0 0 0 0 0 0 –:–:– –:–:– –:–:– 0

******************** 檢查是否禁止root使用者遠端登入 ****************************************

grep: /etc/ssh/sshd_config: Permission denied

[ FAILED ] PermitRootLogin 未設定

% Total % Received % Xferd Average Speed Time Time Time Current

Dload Upload Total Spent Left Speed

0 0 0 0 0 0 0 0 –:–:– –:–:– –:–:– 0

******************** 檢查歷史命令快取 ************************************

[ FAILED ] HISTFILESIZE 未設定

% Total % Received % Xferd Average Speed Time Time Time Current

Dload Upload Total Spent Left Speed

0 0 0 0 0 0 0 0 –:–:– –:–:– –:–:– 0

[ FAILED ] HISTSIZE 設定不當(參考值30),當前值為: 1000

% Total % Received % Xferd Average Speed Time Time Time Current

Dload Upload Total Spent Left Speed

0 0 0 0 0 0 0 0 –:–:– –:–:– –:–:– 0

******************** 檢查umask **********************************************

[ FAILED ] UMASK設定不當,當前值為: 0002

% Total % Received % Xferd Average Speed Time Time Time Current

Dload Upload Total Spent Left Speed

0 0 0 0 0 0 0 0 –:–:– –:–:– –:–:– 0

******************** 檢查主機信任關係 *****************************************

find: /home/caojie: Permission denied

find: /home/zabbix: Permission denied

find: /home/liyong: Permission denied

find: /home/willy: Permission denied

find: /home/oracle: Permission denied

find: /home/liuyang: Permission denied

find: /home/lost+found: Permission denied

find: /home/nagios: Permission denied

find: /home/lengzhenguo: Permission denied

find: /home/mysql: Permission denied

[ OK ] 檢查通過

% Total % Received % Xferd Average Speed Time Time Time Current

Dload Upload Total Spent Left Speed

0 0 0 0 0 0 0 0 –:–:– –:–:– –:–:– 0

******************** 檢查程式、記憶體資源訪問限制 ***********************

[ FAILED ] HARD CORE設定不當,當前值為: unlimited

% Total % Received % Xferd Average Speed Time Time Time Current

Dload Upload Total Spent Left Speed

0 0 0 0 0 0 0 0 –:–:– –:–:– –:–:– 0

[ FAILED ] HARD RSS 未設定

% Total % Received % Xferd Average Speed Time Time Time Current

Dload Upload Total Spent Left Speed

0 0 0 0 0 0 0 0 –:–:– –:–:– –:–:– 0

[ FAILED ] HARD NPROC設定不當,當前值為: 131072

% Total % Received % Xferd Average Speed Time Time Time Current

Dload Upload Total Spent Left Speed

0 0 0 0 0 0 0 0 –:–:– –:–:– –:–:– 0

******************** 檢查su命令限制 **********************************

auth sufficient pam_rootok.so auth include system-auth

% Total % Received % Xferd Average Speed Time Time Time Current

Dload Upload Total Spent Left Speed

0 0 0 0 0 0 0 0 –:–:– –:–:– –:–:– 0

******************** 檢查sudoer賬戶 *********************************************

grep: /etc/sudoers: Permission denied

% Total % Received % Xferd Average Speed Time Time Time Current

Dload Upload Total Spent Left Speed

0 0 0 0 0 0 0 0 –:–:– –:–:– –:–:– 0

******************** 檢查SUID許可權檔案 ***********************************************

% Total % Received % Xferd Average Speed Time Time Time Current

Dload Upload Total Spent Left Speed

100 1519 0 0 100 1519 0 2026 –:–:– –:–:– –:–:– 3273

……………

相關文章